T
T
the5x2020-04-01 11:14:55
recursion
the5x, 2020-04-01 11:14:55

How to recursively change state in an array tree with objects?

There is a tree where the nesting of children can be unlimited. How to get recursively at each map iteration to children and change the state?

const data = [
  {
    id: 1, title: 'Article 1',
    children: [
      {
        id: 1, title: 'Title Inside 1',
        children: [
          {
            id: 1, title: 'Title Inside 2',
          }
      ]
    }]
  },


  { id: 2, title: 'Article 2' },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-04-01
@the5x

something like this, if I understand correctly what needs to be done at all

obj = {
  "id": 1,
  "title": "Article 1",
  "children": [
    {
      "id": 1,
      "title": "Title Inside 1",
      "children": [
        {
          "id": 11,
          "title": "Title Inside 2",
          "children": [
            {
              "id": 121,
              "title": "Title Inside 4"
            },
            {
              "id": 12341,
              "title": "Title Inside 6"
            }
          ]
        }
      ]
    }
  ]
}

function fn(obj, upd) {
  obj = {...obj, ...upd}
  if(Array.isArray(obj.children)) { 
    obj.children = obj.children.map(child => fn(child, upd)) 
  }
  return obj
}

fn(obj, { id: 2, title: 'Article 2' })

this is for one object, but it should be possible to map an array of such elements with such a function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question