【问题标题】:Update a value in a nested array while maintaining original indexes ES6 [duplicate]更新嵌套数组中的值,同时保持原始索引 ES6 [重复]
【发布时间】:2018-11-20 21:14:26
【问题描述】:

我想更新嵌套数组中的值并返回更新后的数组。这都应该在 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
            }
        ]
    }]
}];

感谢您的帮助。

【问题讨论】:

  • 您想要更新还是使用更新后的项目获得全新的数据结构?顺便说一句,你试过什么?
  • 你需要像地图这样的东西,然后是所有孩子的递归函数
  • 你环顾四周了吗?这个问题之前肯定被问过很多次了。

标签: javascript ecmascript-6


【解决方案1】:

你可以通过递归函数来做这样的事情:

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)

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

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 2018-04-26
    • 1970-01-01
    • 2023-02-13
    • 2016-05-31
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2017-01-13
    相关资源
    最近更新 更多