-1

I have an object of which the depth may increase when I fetch the api.

Supposing it was a parent with children it would initially look something like this.

{
  name: 'Mary'
  children: [
    {name: 'Jude'},
    {name: 'Kathy'},
    {name: 'Joe'}
  ]
}

Now I want fetch the API and get Kathy's children

The response is the object for Kathy with her children

suppose:

{
  name: 'Kathy',
  children: [
    {name: 'April'},
    {name: 'Suzanne'},
    {name: 'Paul'}
  ]
}

So I want to end up having

{
  name: 'Mary'
  children: [
    {
      name: 'Jude'
    },
    {
      name: 'Kathy',
      children: [
        {name: 'April'},
        {name: 'Suzanne'},
        {name: 'Paul'}
      ]
    },
    {
      name: 'Joe'
    }
  ]
}

And maybe then get Paul's or Joe's

If I know the depth before hand, I could do for the first example

newObj = { ...oldObj, children: { ...oldObj.children, ...apiResponse }}

right?

But what about when the depth is variable (not unknown but variable)?

How would I do this?

Thank you

user3808307
  • 2,270
  • 9
  • 45
  • 99
  • If you know the `index` of `Kathy`, then just `object.children[index] = yourNewObject` – r3wt Dec 16 '19 at 19:31
  • @r3wt I know the index of Kathy, but Kathy is no necessarily in the first layer. I could have Kathy buried deep several levels in, like object.children[index].children[index1].children[index2]. So even if I know index and index1 and index2 and how many levels deeps, I don't know how to write it in code – user3808307 Dec 16 '19 at 19:38
  • show your full code then – r3wt Dec 16 '19 at 19:39
  • @r3wt I just edited my comment with a better explanation. I don't have a full code, I am trying to make an object – user3808307 Dec 16 '19 at 19:40
  • you haven't provided enough details for your question to be answered, and as such i have voted to close. – r3wt Dec 16 '19 at 19:45
  • @r3wt You have not understood the question, and and as such you are voting to close it. The whole point of the question is that the depth in which to add the new object is variable. It says so in the title – user3808307 Dec 16 '19 at 19:46

1 Answers1

1

Something like this?

function find(name, node) {

 if (node.name == name){
   return node;
  }
  
  if (node.children) {
   for(const child of node.children){
     const match = find(name, child);
      if(match){
       return match;
      }
    }
  }
  
  return null;
}

const root =  {
  name: 'Mary',
  children: [
    {name: 'Jude'},
    {name: 'Kathy'},
    {name: 'Joe'}
  ]
};

const match = find("Kathy",root);

const fullNode = {
  name: 'Kathy',
  children: [
    {name: 'April'},
    {name: 'Suzanne'},
    {name: 'Paul'}
  ]
}

Object.assign(match, fullNode);

console.log(root);
typesafe
  • 176
  • 3