我有一个对象数组:
const array = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 }
];
并且我需要向其添加另一个条目,但是它需要可放置在数组中的任何位置。因此,例如:
array.push({ id: 5, after_id: 2 });
并将新条目放置在ID2
和之间3
。有一些标准的方法吗?
@pswg已经在评论中发布了可能是最好的解决方案,但是我认为我现在将我原来的解决方案发布为答案,因为现在已经重新打开了。
您可以使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句