简体   繁体   中英

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). Update my state and display it on the screen.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM