筛选包含特定值的多维数组

时间:2019-06-16 00:43:01

标签: javascript arrays object filter

我有一个数组...

var families = [
  {
    family:"Jones",
    kids: [
      {name:"Kelly", gender:'female'},
      {name:"Mike", gender:'male'},
      {name:"Bill", gender:'male'}
    ]
  },{
    family:"Smiths",
    kids: [
      {name:"Roger", gender:'male'}
    ]
  }
]

...我需要筛选并按性别分类家庭。因此,如果我搜索“女性”,则需要一系列包含女性家庭的家庭。无论家庭中是否有男性。因此,在上面的代码中,如果我搜索女性,那么只有一个家庭会返回。但是,如果我按男性搜寻,将会有2个家庭返回。

我的尝试如下:

var filter = 'female';
filteredList = families.filter(function (family) {
  return family.kids.filter(function (kid) {
    return kid.gender.toLowerCase().indexOf(filter) !== -1;
  })
})

我不能正确退还吗?

3 个答案:

答案 0 :(得分:2)

您应该像这样使用filtersome

var families=[{family:"Jones",kids:[{name:"Kelly",gender:'female'},{name:"Mike",gender:'male'},{name:"Bill",gender:'male'}]},{family:"Smiths",kids:[{name:"Roger",gender:'male'}]}];
var filter = "female";
const res = families.filter(({ kids }) => kids.some(({ gender }) => gender == filter));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5语法:

var families=[{family:"Jones",kids:[{name:"Kelly",gender:'female'},{name:"Mike",gender:'male'},{name:"Bill",gender:'male'}]},{family:"Smiths",kids:[{name:"Roger",gender:'male'}]}];
var filter = "female";
var res = families.filter(function(family) {
  return family.kids.some(function(kid) {
    return kid.gender == filter;
  })
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 1 :(得分:0)

除了一个小细节,您的代码基本上就在那里:内部过滤器向外部过滤器返回一个空数组,该数组始终被评估为true。将.length添加到内部数组以使空数组变为false:

var families = [ { family:"Jones", kids: [ {name:"Kelly", gender:'female'}, {name:"Mike", gender:'male'}, {name:"Bill", gender:'male'} ] },{ family:"Smiths", kids: [ {name:"Roger", gender:'male'} ] } ];

var filter = 'female';
filteredList = families.filter(function (family) {
  return family.kids.filter(function (kid) {
    return kid.gender.toLowerCase().indexOf(filter) !== -1;
  }).length
  //^^^^^^^
});

console.log(filteredList);

答案 2 :(得分:0)

您可以使用forEachsomeforEach将用于遍历数组,并使用some查找kids中的任何对象是否具有所需的性别。

var families = [{
  family: "Jones",
  kids: [{
      name: "Kelly",
      gender: 'female'
    },
    {
      name: "Mike",
      gender: 'male'
    },
    {
      name: "Bill",
      gender: 'male'
    }
  ]
}, {
  family: "Smiths",
  kids: [{
    name: "Roger",
    gender: 'male'
  }]
}];


let filteredData = function(arr, gender) {
  let filteredFamily = [];
  arr.forEach(function(elem) {
    let ifHasGender = elem.kids.some(function(item) {
      return item.gender === gender
    })
    if (ifHasGender) {
      filteredFamily.push(elem)
    }
  })

  return filteredFamily;
}

console.log(filteredData(families, 'female'))