Home > Mobile >  How to access last object inside nested array of objects and update its property without passing id
How to access last object inside nested array of objects and update its property without passing id

Time:11-05

I want to access last object inside nested array of objects and change its property value, I don't know its id or any any other property value

const arr = [ {id: 1, comment:'parent 01', parentId:null, reply:true, children:[{id: 11, comment:'child', reply:true, parentId:1, children:[{id: 21, comment:'super child ', reply:true,parentId:11 }] }] }, {id: 2, comment:'parent 02', reply:true, parentId:null } ]

I want to access this below object and change its property value:

{id: 21, comment:'super child ', reply:true, parentId:11 }

// result should be:
{id: 21, comment:'super child ', reply:false, parentId:11 }

CodePudding user response:

Need to do it recursively and when the depth is greater than 0 and it doesn't have any children then need to modify the object(s).

const arr = [{
  id: 1,
  comment: 'parent 01',
  parentId: null,
  reply: true,
  children: [{
    id: 11,
    comment: 'child',
    reply: true,
    parentId: 1,
    children: [{
      id: 21,
      comment: 'super child ',
      reply: true,
      parentId: 11
    }]
  }]
}, {
  id: 2,
  comment: 'parent 02',
  reply: true,
  parentId: null
}];


const build = (arr, depth) => {
  const nodes = [];
  arr.forEach((val) => {
    if (depth > 0 && !val["children"]) { //Base case
      nodes.push({ ...val,
        reply: false
      });
      return;
    }
    nodes.push(val["children"] ? { ...val,
      "children": build(val["children"], depth   1)
    } : val);
  });

  return nodes;
}

console.log(build(arr, 0));

  • Related