gpt4 book ai didi

javascript - 过滤对象数组

转载 作者:行者123 更新时间:2023-11-28 08:43:22 25 4
gpt4 key购买 nike

我有一组带有 id/nume 的数组(对象):

Object { Biosecuritate=[Object {id=1,nume="bio"}, 
Object {id=5,nume="securitate"}], Deseuri=[Object {id=2,nume="des"}] ,
Reglementari=[Object {id=3,nume="Reglementari"}],
Sol/Subsol=[Object {id=4,nume="Sol/Subsol"}] }

var filtered = _.filter(domenii, function(item) {
return (item[0].nume == "Reglementari" || item[0].nume == "Sol/Subsol")
});
console.log("filtered=",filtered);
console.log("domenii=",domenii);

我试图从“矩阵”中仅“提取”2个对象,但在执行过滤器之后它变成:

[ [Object {id=3,nume="Reglementari"}], [Object {id=4,nume="Sol/Subsol"}] ]

如何将“已过滤”转换为初始类型,或在不更改其“形式”的情况下对其进行过滤?

最佳答案

要维护对象,您可以减少而不是过滤:

var domenii = {
Biosecuritate: [{id:1,nume:"bio"}, {id:5,nume:"securitate"}],
Deseuri: [{id:2,nume:"des"}] ,
Reglementari: [{id:3,nume:"Reglementari"}],
"Sol/Subsol": [{id:4,nume:"Sol/Subsol"}]
}

var reduced = _.reduce(domenii, function(memo, item, key){
if(item[0].nume == "Reglementari" || item[0].nume == "Sol/Subsol"){
memo[key] = item;
}
return memo
}, {})

console.log("reduced=",reduced);
console.log("domenii=",domenii);

关于javascript - 过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218717/

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