gpt4 book ai didi

javascript - 对象数组 : return only objects (and children) where attribute matches

转载 作者:行者123 更新时间:2023-11-28 15:12:47 24 4
gpt4 key购买 nike

我有一个包含多个“级别”或子级的数组。我想创建一个新的对象数组,其中 archived===false 以便不列出任何已归档的对象。

所以这个...

var arr = [
{"id":1, "archived":false,"children":[
{"id":1,"archived":true, "subs":[
{"id":1,"archived":true},
{"id":2,"archived":true},
{"id":3,"archived":true}
]},
{"id":2,"archived":false, "subs":[
{"id":1,"archived":false},
{"id":2,"archived":false},
{"id":3,"archived":true}
]}
]},
{"id":2, "archived":true,"children":[
{"id":1,"archived":true, "subs":[
{"id":1,"archived":true},
{"id":2,"archived":true},
{"id":3,"archived":true}
]},
{"id":2,"archived":true, "subs":[
{"id":1,"archived":true},
{"id":2,"archived":true},
{"id":3,"archived":true}
]}
]},
{"id":3, "archived":false,"children":[
{"id":1,"archived":false, "subs":[
{"id":1,"archived":true},
{"id":2,"archived":false},
{"id":3,"archived":true}
]},
{"id":2,"archived":false, "subs":[
{"id":1,"archived":false},
{"id":2,"archived":false},
{"id":3,"archived":false}
]}
]}
];

成为...

var arr = [
{"id":1, "archived":false,"children":[
{"id":2,"archived":false, "subs":[
{"id":1,"archived":false},
{"id":2,"archived":false}
]}
]},
{"id":3, "archived":false,"children":[
{"id":1,"archived":false, "subs":[
{"id":2,"archived":false}
]},
{"id":2,"archived":false, "subs":[
{"id":1,"archived":false},
{"id":2,"archived":false},
{"id":3,"archived":false}
]}
]}
];

我尝试过map、reduce、filter和grep的组合...但我可能没有正确的顺序,等等。我知道我可以循环遍历每个级别,但我无法得到它对。

如果能将其包含在 linq.js 可枚举数组或 jQuery 中,那就太好了。

Non-working Example fiddle

最佳答案

精心设计的处理递归的函数可以使使用 linq.js 实现这一点变得相当简单。特别是这不一定需要 linq.js,但它保持简单。

function isNotArchived(childrenName, childrenFilter) {
return function (e) {
var filtered = e.Where("!$.archived");
if (childrenName && childrenFilter) {
return filtered.Select(function (c) {
var result = { id: c.id, archived: c.archived };
result[childrenName] = $.Enumerable.From(c[childrenName])
.Let(childrenFilter)
.ToArray();
return result;
});
}
return filtered;
};
}
var filtered = $.Enumerable.From(arr)
.Let(isNotArchived("children",
isNotArchived("subs",
isNotArchived()
)
))
.ToArray();

fiddle

关于javascript - 对象数组 : return only objects (and children) where attribute matches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514148/

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