-3

I have such an array

const arr = [
    {id: 1, title: 'qwer', children: []},
    {id: 2, titile: 'sparta', children: 
      [
       {id: 21, title: 'sdf', children: []},
       {id: 11, title: 'change me', children: []}
      ]
    }
  ]

I need to edit an object {id: 11, title: 'change me', children: []}; I am doing this in this way

const newData = dataCopy.map(el => {
          if(el.Id === this.titleId){
            return {
              ...el,
              Title: val
            }
          }
          return el;
        });

The problem is that i dont know how to find target object in sub array. How can i find it and return new array?

Farooq Ahmed Khan
  • 3,975
  • 3
  • 27
  • 36
Sasha Zoria
  • 739
  • 1
  • 9
  • 28

1 Answers1

-1

You could create a function like the following:

function editCopy(arr, id, val) {
    return arr.map(item => ({
        ...item,
        title: item.id === id ? val : item.title,
        children: editCopy(item.children, id, val)
    }));
}

and then call the function with the given array as the first parameter, the id of the element you want to change as the second parameter and the value you want to change to as the third parameter. For example, in your case,

const newData = editCopy(arr, 11, '...some changed value...')

The function will return a new array with the value of the element with the given id being changed.

The function uses recursion to check and change the value in 'children' array as well.

Hope this helps.