使用 Javascript 在嵌套数组中查找值,并使用以下信息添加或更新相关数组。 搜索id:jkl
并在相关数组{values:123,field:'Field Name'}
中添加以下键和值。
嵌套数组
[{
id: "abc",
name: "Parent Object",
children: [{
id: "def",
name: "Child 1 Object",
parentId: "abc",
children: [{
id: "ghi",
name: "Child 2 Object",
parentId: "def",
children: [{
id: "jkl",
name: "Child 3 Object",
parentId: "ghi",
}]
}]
}]
}]
谢谢
你要找的是一个递归函数。
const data = [{
id: "abc",
name: "Parent Object",
children: [{
id: "def",
name: "Child 1 Object",
parentId: "abc",
children: [{
id: "ghi",
name: "Child 2 Object",
parentId: "def",
children: [{
id: "jkl",
name: "Child 3 Object",
parentId: "ghi",
}]
}]
}]
}]
function findNested (arr, id) {
for (let item of arr) {
if (item.id === id) return item // item found, return the current obj
if (item.children instanceof Array) {
// magic happens here
return findNested(item.children, id)
}
}
return null // nothing found
}
const obj = findNested(data, 'jkl')
// obj is a reference here. Changing it will also change the object in `data`
obj.values = 123
console.log(data)
您可以构建一个递归函数来实现这一点:
const arr = [{ id: "abc", name: "Parent Object", children: [{ id: "def", name: "Child 1 Object", parentId: "abc", children: [{ id: "ghi", name: "Child 2 Object", parentId: "def", children: [{ id: "jkl", name: "Child 3 Object", parentId: "ghi", }] }] }]}];
const getUpdated=(arr,obj, id)=>{
return arr.map(k=> k.id == id ? ({...k, ...obj}) : ({...k, children: k.children ? getUpdated(k.children, obj, id) : []}))
};
console.log(getUpdated(arr, {values:123,field:'Field Name'}, 'jkl')); // updated array returned