问题
Let's say I have an object where the values are arrays, like this:
{
123456: ['apple','orange','banana'],
987654: ['dog','cat','mouse'],
112233: ['car','truck','bike']
}
and that I have access to 2 variables, itemID that has the key assigned to it, and the array index of the item I want to remove. For example
itemID = 987654;
n = 1;
So the resulting object I want to get would be
{
123456: ['apple','orange','banana'],
987654: ['dog','mouse'],
112233: ['car','truck','bike']
}
I need to write a function
removeItem(itemID, n) {
}
What would be the best way to do it?
回答1:
Here is the solution
var obj = {
123456: ['apple','orange','banana'],
987654: ['dog','cat','mouse'],
112233: ['car','truck','bike']
}
function removeItem(itemID, n) {
if(!obj[itemID]) {
return;
}
obj[itemID].splice(n, 1);
}
removeItem(987654, 1);
console.log(obj);
I'll add some explanation, To access object by key you : obj[key];
Array.splice in this case, meaning(splice(n, 1)) - take the item at index n and remove exactly one item from that index;
One more note :
when you access object the key should be a string
So I'l change
removeItem(987654, 1);
To:
removeItem('987654', 1);
It will work in both ways thow.
回答2:
It can be done using splice method:
const removeItem = (itemID, n) => {
if (!foo[itemID])
return;
foo[itemID].splice(n,1);
return foo;
}
An example:
var foo = {
123456: ['apple','orange','banana'],
987654: ['dog','cat','mouse'],
112233: ['car','truck','bike']
};
const removeItem = (itemID, n) => {
if (!foo[itemID])
return;
foo[itemID].splice(n, 1);
return foo;
}
console.log(removeItem(987654, 1));
回答3:
var obj = /*ur obj*/
var itemID = 987654;
var n = 1;
removeItem(itemID, n) {
let str = obj[itemID][n];
this.obj[itemID] = obj[itemID].filter(item => item != str);
}
回答4:
Try this:
<!DOCTYPE html>
<html>
<body onload="removeItem(987654,1)">
<p id="demo"></p>
<script>
var data ={
123456: ['apple','orange','banana'],
987654: ['dog','cat','mouse'],
112233: ['car','truck','bike']
};
function removeItem(itemID, n) {
data[itemID] = data[itemID].filter(function(value, index, array) {
return index != n;
});
document.getElementById("demo").innerHTML = JSON.stringify(data);
}
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/59477367/accessing-an-array-inside-a-js-object-and-removing-an-item-from-it-by-index