访问JS对象内部的数组并按索引从中删除一个项目 [英] Accessing an array inside a JS object and removing an item from it by index
问题描述
假设我有一个对象,其中的值是数组,像这样:
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']
}
并且我可以访问2个变量,即具有键的itemID分配给它,以及我要删除的项目的数组索引。
例如
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']
}
我需要编写一个函数
removeItem(itemID, n) {
}
最好的方法是什么?
推荐答案
这是解决方案
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);
我将添加一些解释,
要通过键访问对象,您可以:obj [key ];
I'll add some explanation, To access object by key you : obj[key];
Array.splice在这种情况下,
的意思是(splice(n,1))-取索引n处的项,并从中精确删除一项该索引;
Array.splice in this case, meaning(splice(n, 1)) - take the item at index n and remove exactly one item from that index;
另外一个注意事项:
,当您访问对象时,键应该是字符串
,所以我将
removeItem(987654,1);
收件人:
removeItem('987654',1);
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.
这篇关于访问JS对象内部的数组并按索引从中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!