我有一个对象数组。每个对象还可以包含一个对象数组,依此类推到任意深度。
var myArray = [
{
id:'foo',
items:[]
},
{
id:'bar',
items:[
{
id:'blah'
items:[...etc...]
}
]
}
]
我想使用索引数组读取、添加和删除嵌套数组中的对象。
因此,将使用此索引数组作为参数来调用从 myArray
中删除值 myArray[1][3][2]
的函数:[1,3,2]
我发现您可以使用 reduce()
来返回如下所示的值:
indices.reduce((acc, cur) => Array.isArray(acc) ? acc[cur] : acc.items[cur], myArray)
但无法弄清楚如何使用相同的想法删除或添加值。非常感谢任何帮助。
最佳答案
您可以创建一个函数,它采用与 splice
类似的参数。功能。传递嵌套数组 indices
路径,要删除的项目总数,并使用 rest parameters 收集要在末尾添加的所有新项目。
function deepSplice(array, indices, deleteCount, ...toBeInserted) {
const last = indices.pop();
const finalItems = indices.reduce((acc, i) => acc[i].items, array);
finalItems.splice(last, deleteCount, ...toBeInserted);
return array
}
- 从
indices
中删除最后一个索引大批。 -
reduce
indices
数组来获取嵌套items
每个循环中的数组以获得最终的items
您要对其执行插入/删除操作的数组。 - 使用
splice
关于last
根据传递的参数插入/删除的索引。
如果你只是想插入,则传递deleteCount = 0
。如果您只想删除,请跳过最后一个参数。
这是一个片段:
const myArray = [
{ id: "0", items: [] },
{
id: "1",
items: [
{
id: "1.0",
items: [
{ id: "1.0.0", items: [] },
{ id: "1.0.1", items: [] }]
},
{ id: "1.1", items: [] }
]
}
];
function deepSplice(array, indices, deleteCount, ...toBeInserted) {
const last = indices.pop();
const finalItems = indices.reduce((acc, i) => acc[i].items, array);
finalItems.splice(last, deleteCount, ...toBeInserted);
return array
}
console.log(
// removes "1.0.1" item and inserts a new object there
deepSplice(myArray, [1,0,1], 1, { id: 'newlyInserted'})
)
关于javascript - 在 Javascript 中使用索引数组访问和修改任意深度的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62268544/