find and modify deeply nested object in javascript array

前端 未结 6 1848
情深已故
情深已故 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:49

    I needed to modify deeply nested objects too, and found no acceptable tool for that purpose. Then I've made this and pushed it to npm.

    https://www.npmjs.com/package/find-and

    This small [TypeScript-friendly] lib can help with modifying nested objects in a lodash manner. E.g.,

    var findAnd = require("find-and");
    
    const data = {
      name: 'One',
      description: 'Description',
      children: [
        {
          id: 1,
          name: 'Two',
        },
        {
          id: 2,
          name: 'Three',
        },
      ],
    };
    
    findAnd.changeProps(data, { id: 2 }, { name: 'Foo' });
    

    outputs

    {
      name: 'One',
      description: 'Description',
      children: [
        {
          id: 1,
          name: 'Two',
        },
        {
          id: 2,
          name: 'Foo',
        },
      ],
    }
    

    https://runkit.com/embed/bn2hpyfex60e

    Hope this could help someone else.

提交回复
热议问题