find and modify deeply nested object in javascript array

前端 未结 6 1879
情深已故
情深已故 2021-01-06 12:11

I have an array of objects that can be of any length and any depth. I need to be able to find an object by its id and then modify that object within the array. Is there an

6条回答
  •  感动是毒
    2021-01-06 12:56

    If each object has property with the same name that stores other nested objects, you can use: https://github.com/dominik791/obj-traverse

    findAndModifyFirst() method should solve your problem. The first parameter is a root object, not array, so you should create it at first:

    var rootObj = {
      name: 'rootObject',
      children: [
        {
          'name': 'child1',
           children: [ ... ]
        },
        {
           'name': 'child2',
           children: [ ... ]
        }
      ]
    };
    

    Then use findAndModifyFirst() method:

    findAndModifyFirst(rootObj, 'children', { id: 1 }, replacementObject)
    

    replacementObject is whatever object that should replace the object that has id equal to 1.

    You can try it using demo app: https://dominik791.github.io/obj-traverse-demo/

提交回复
热议问题