过滤对象数组

时间:2013-11-26 13:43:25

标签: javascript arrays object underscore.js

我有一个数组(对象)的aray / id:

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"}] ]

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

2 个答案:

答案 0 :(得分:0)

domenii的类型更改为平面数组可能会更好,但您也可以将结果展平。将其添加到最后:filtered = _.flatten(filtered);

答案 1 :(得分:0)

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

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);