gpt4 book ai didi

javascript - 过滤JavaScript中具有相同嵌套属性的对象数组

转载 作者:行者123 更新时间:2023-12-02 21:25:12 25 4
gpt4 key购买 nike

[{"code":"96","value":"RemoveTest","parentLabelCode":1,"color":null,"level":1,"children":[{"code":"97","value":"R1","parentLabelCode":96,"color":null,"level":2,"children":[],"visible":true,"retired":false,"systemLabel":true,"removeOnArchive":true,"displayNumber":1,"labelTranslations":null},{"code":"98","value":"R2","parentLabelCode":96,"color":null,"level":2,"children":[],"visible":true,"retired":true,"systemLabel":true,"removeOnArchive":true,"displayNumber":2,"labelTranslations":null},{"code":"99","value":"R3","parentLabelCode":96,"color":null,"level":2,"children":[],"visible":true,"retired":true,"systemLabel":true,"removeOnArchive":true,"displayNumber":2,"labelTranslations":null}],"visible":true,"retired":false,"systemLabel":true,"removeOnArchive":true,"displayNumber":0,"labelTranslations":null}]

我想要这个输出:基于退休:假,退休:真过滤,不应该显示并且有多个对象并且有深层嵌套的子项,我正在递归执行但没有得到预期的输出

 var list = label_lists.filter(function f(item) {
return item.retired==false ||
item.children && (item.children = item.children.filter(f)).length
})

[{"code":"96","value":"RemoveTest","parentLabelCode":1,"color":null,"level":1,"children":[{"code":"97","value":"R1","parentLabelCode":96,"color":null,"level":2,"children":[],"visible":true,"retired":false,"systemLabel":true,"removeOnArchive":true,"displayNumber":1,"labelTranslations":null}],"visible":true,"retired":false,"systemLabel":true,"removeOnArchive":true,"displayNumber":0,"labelTranslations":null}]

最佳答案

这是一个递归解决方案,它也复制而不是修改源对象:

function notRetired(arr) {
return arr.filter(item => !item.retired)
.map(item => Object.assign({}, item, {
children: notRetired(item.children)
}));
}

这是一个(有点老套的)变体,适用于循环结构:

function notRetired(arr, cache = null) {
return arr.filter(item => !item.retired)
.map((item, ret) => (cache || (cache = new Map())).get(item) ||
(cache.set(item, ret = {}) && Object.assign(ret, item, {
children: notRetired(item.children, cache)
})));
}

关于javascript - 过滤JavaScript中具有相同嵌套属性的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60757840/

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