0

I want to update a value in a nested array and return the updated array. This should all be in ES6. I may have over 2000 children and I have only the id from the object that should be updated.

My array looks like:

let data = [{
    title: 'Name 1',
    key: '0-0',
    children: [{
        title: 'Name 1-1',
        key: '0-0-0',
        id: 4,
        children: [{
                title: 'Name 1-3',
                key: '0-0-0-0',
                id: 3,
                visibility: false,
                children: [{
                    title: 'Name 1-4',
                    key: '0-0-0-0',
                    id: 34,
                    visibility: false // this need to be updated
                }]
            },
            {
                title: 'Name 2-1',
                key: '0-0-1',
                id: 1,
                visibility: false
            }
        ]
    }]
}];

Thanks for help.

Josh
  • 800
  • 6
  • 8
GoranR
  • 97
  • 7

1 Answers1

2

You can do something like this via a recursive function:

let data = [{ title: 'Name 1', key: '0-0', children: [{ title: 'Name 1-1', key: '0-0-0', id: 4, children: [{ title: 'Name 1-3', key: '0-0-0-0', id: 3, visibility: false, children: [{ title: 'Name 1-4', key: '0-0-0-0', id: 34, visibility: false }] }, { title: 'Name 2-1', key: '0-0-1', id: 1, visibility: false } ] }] }]

const findById = (data, id) => {
  var found, s = (d, id) => d.find(x => x.id == id ? found = x : s(x.children, id))    
  s(data, id)
  return found ? found : false
}

let el = findById(data, 34)
el.visibility = true

console.log(el)
console.log(data)

This will also find the element and return it so you can change anything you want on it.

Akrion
  • 18,117
  • 1
  • 34
  • 54