我有一个对象数组:
const array = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 }
];
我需要向它添加另一个条目,但它需要可放置在数组中的任何位置。例如:
array.push({ id: 5, after_id: 2 });
这应该将新条目放在 ids 2
和 3
。有一些标准的方法可以做到这一点吗?
最佳答案
@p.s.w.g已经在评论中发布了可能是最佳解决方案的内容,但我想我应该在此处发布我的原始解决方案作为答案,现在它已重新打开。
您可以使用 some
遍历数组直到找到正确的索引,然后您可以切片数组并将项目插入相关索引:
const arrayTest = [{
id: 1
},
{
id: 2
},
{
id: 3
},
{
id: 4
}
];
const insertAfterId = (array, item, idAfter) => {
let index = 0;
array.some((item, i) => {
index = i + 1;
return item.id === idAfter
})
return [
...array.slice(0, index),
item,
...array.slice(index, array.length),
];
};
const result = insertAfterId(arrayTest, {
id: 6
}, 2)
console.dir(result)
关于javascript - JS如何给数组的特定位置添加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402359/