javascript - 更新嵌套数组中的值,同时保持原始索引 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
}
]
}]
}];
感谢帮助。
解决方案
您可以通过递归函数执行以下操作:
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)
这也将找到元素并将其返回,以便您可以更改任何您想要的内容。
推荐阅读
- powershell - 将每个子目录的内容移动到文件夹
- django - 如何从弹出模式引导程序中的链接运行函数
- c# - 很难理解级联删除的工作原理以及如何配置关系
- c# - 如何知道一个小时的文件夹中是否没有新文件
- batch-file - 尝试批量制作“操作系统”
- visual-studio - 在 Visual Studio 2019 中调试时 Dockerfile 似乎没有运行
- reactjs - 如何在没有 redux saga 的情况下调用 reducer 操作
- python-3.x - 无法使用 python 编辑 Heroku 上托管的文件
- powershell - 将经典 SharePoint 页面转换为新式时出错 - 索引超出范围
- python - 如何动态使用不影响整个环境的产量