首页 > 解决方案 > 更新嵌套数组中的值,同时保持原始索引 ES6

问题描述

我想更新嵌套数组中的值并返回更新后的数组。这都应该在 ES6 中。我可能有超过 2000 个孩子,我只有应该更新的对象的 id。

我的数组看起来像:

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
            }
        ]
    }]
}];

感谢帮助。

标签: javascriptecmascript-6

解决方案


您可以通过递归函数执行以下操作:

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)

这也将找到元素并将其返回,以便您可以更改任何您想要的内容。


推荐阅读