gpt4 book ai didi

javascript - 更新嵌套数组中的值,同时保留原始索引 ES6

转载 作者:行者123 更新时间:2023-12-03 00:42:13 24 4
gpt4 key购买 nike

我想更新嵌套数组中的值并返回更新后的数组。这一切应该都在 ES6 中。我可能有超过 2000 个 child ,但我只有应该更新的对象的 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)

这还将找到该元素并返回它,以便您可以对其进行任何更改。

关于javascript - 更新嵌套数组中的值,同时保留原始索引 ES6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53401632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com