[英]How do you iterate through a nested array of objects and update an object in JavaScript?
I want to iterate through the nested objects and add a child to a specific object (Maria Jhonson with id = 201).我想遍历嵌套对象并将子对象添加到特定的 object(ID = 201 的 Maria Jhonson)。 Update my state and display it on the screen.更新我的 state 并将其显示在屏幕上。
root = [{
id: 105,
name: "Jhon Doe",
children: [{
id: 106,
name: "Alicia Thomber",
children: [{
id: 101,
name: "Sven Mortensen",
children: []
}]
},
{
id: 110,
name: "Alan Steiner",
children: [{
id: 107,
name: "Jack Wills",
children: [{
id: 101,
name: "David Wilson",
children: [{
id: 115,
name: "Amy Alberts",
children: [{
id: 201,
name: "Maria Jhonson",
children: []
}]
}]
}]
}]
}]
}]
I'm not sure that got you correctly.我不确定你是否正确。 But you can try this func但是你可以试试这个功能
function changeDataById(data, id, newData) {
if (Array.isArray(data)) {
data.forEach(item => {
if (item?.id === id) {
// Do your magic here
return Object.assign(item, newData);
} else if (item.children) {
changeDataById(item.children, id, newData)
}
})
}
}
I already linked SO question on how to traverse a tree.我已经链接了关于如何遍历树的问题。 Only thing is you don't return the element, but push to its children.唯一的问题是您不返回元素,而是推送给它的子元素。
const root = [ { id: 105, name: "Jhon Doe", children: [{ id: 106, name: "Alicia Thomber", children: [{ id: 101, name: "Sven Mortensen", children: [] }] }, { id: 110, name: "Alan Steiner", children: [{ id: 107, name: "Jack Wills", children: [{ id: 101, name: "David Wilson", children: [{ id: 115, name: "Amy Alberts", children: [{ id: 201, name: "Maria Jhonson", children: [] }] }] }] }] } ] }] const _insertValue = (node, id, value) => { node.forEach(child => insertValue(child, id, value)) return node } const insertValue = (node, id, value) => { const stack = [] let i stack.push(node); while (stack.length > 0) { node = stack.pop(); if (node.id === id) { node.children.push(value) return node; } else if (node.children?.length) { for (i = 0; i < node.children.length; i++) { stack.push(node.children[i]); } } } return null; } const res = _insertValue(root, 201, { id: "202", name: "test", children: [] }) console.log(res) //inserted id 202 as a child of 201
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.