[英]Javascript iterate through nested Object and return transformed and renamed Array of objects
[英]How do you iterate through a nested array of objects and update an object in JavaScript?
我想遍歷嵌套對象並將子對象添加到特定的 object(ID = 201 的 Maria Jhonson)。 更新我的 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: []
}]
}]
}]
}]
}]
}]
我不確定你是否正確。 但是你可以試試這個功能
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)
}
})
}
}
我已經鏈接了關於如何遍歷樹的問題。 唯一的問題是您不返回元素,而是推送給它的子元素。
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.