2

This example has a great reason how to update the object. But have one problem, this only works on objects at same level (depth).

How can I do something the same but with more of level one, depth?

I have an example object here :

let globalObj = [
    {
      fam_id: 1, // Random unique ID's.
      name: "No name",
      attributes: {
        "Key2": "*",
        "Key3": "*",
      },
      children: [
        {
          fam_id: 2, // Random unique ID's.
          name: "No name 2",
          attributes: {
            "Key2": "*",
            "Key3": "*",
          },
        },
      ],
    },
  ]

I have here object to update global, e.g :

let updateObj = {        
        fam_id: 2, // Mathed ID!
        name: "No name 3",
        attributes: {
            "Key2": "*",
            "Key3": "*",
         },
},

findIndex and slice methods works very well, but for depth 0? How to filter more of depth 0? How about 1 or more?

Thanks! o/

Milos N.
  • 4,416
  • 6
  • 18
  • 31

1 Answers1

1

You can accomplish this by using a recursive function

let globalObj = [
    {
      fam_id: 1, // Random unique ID's.
      name: "No name",
      attributes: {
        "Key2": "*",
        "Key3": "*",
      },
      children: [
        {
          fam_id: 2, // Random unique ID's.
          name: "No name 2",
          attributes: {
            "Key2": "*",
            "Key3": "*",
          },
        },
      ],
    },
  ];

let updateObj = {        
        fam_id: 2, // Mathed ID!
        name: "No name 3",
        attributes: {
            "Key2": "*",
            "Key3": "*",
         },
};

// recursive function
matchAndUpdate = (updater, target) => {
    if (updater.fam_id === target.fam_id) {
        target.name = updater.name;
        target.attributes = updater.attributes;
    }
    
    if ("children" in target && Array.isArray(target.children)) {
        target.children.forEach(child => {
            matchAndUpdate(updater, child);
        });
    }
}

globalObj.forEach(g => {matchAndUpdate(updateObj,g )});

document.getElementById('x').innerText = JSON.stringify(globalObj,null,"\t");
pre {
  background-color: #456;
  color: #FED;
  font-size: small;
}
<pre><code id="x"></code></pre>
code_monk
  • 9,451
  • 2
  • 42
  • 41