筛选对象必须符合所有条件的对象数组

时间:2018-08-01 18:33:08

标签: javascript arrays object

我需要解析对象的数组和我知道可以使用.filter()进行处理的嵌入式对象数组。但是,我需要检查嵌入式数组是否具有多种对象中的至少一种。请参见下面的示例:

我有一组Garage对象,这些对象具有一个“ cars”字段,该字段是一组汽车。每辆汽车都是具有多种品质的物体。我需要查看哪个车库至少有一辆“快速”汽车和至少一辆“微型”汽车。如果两种品质都属于同一辆车,也可以。用javascript完成此操作的最快/最有效的方法是什么?

garageArray = [
 {
  id: 10,
  cars: [
   {id: 1, qualities: ["fast", "small"]},
   {id: 2, qualities: ["offRoad", "large"]},
   {id: 3, qualities: ["fast", "loud"]}
  ]
 },
 {
  id: 20,
  cars: [
   {id: 4, qualities: ["loud"]},
   {id: 5, qualities: ["fast", "tiny"]}
  ]
 },
 {
  id: 30,
  cars: [
   {id: 6, qualities: ["slow", "small"]},
   {id: 7, qualities: ["offRoad", "tiny"]},
   {id: 8, qualities: ["fast", "loud"]}
  ]
 }
]

结果应该是ID为20和30的车库。

2 个答案:

答案 0 :(得分:2)

这应该做到:

garageArray.filter(garage =>
    garage.cars.some(car => car.qualities.includes("fast")) &&
    garage.cars.some(car => car.qualities.includes("tiny"))
);

但是,匹配 n 属性的更通用的解决方案如下:

const garageArray = [
    {
        id: 10,
        cars: [
            { id: 1, qualities: ["fast", "small"] },
            { id: 2, qualities: ["offRoad", "large"] },
            { id: 3, qualities: ["fast", "loud"] }
        ]
    },
    {
        id: 20,
        cars: [
            { id: 4, qualities: ["loud"] },
            { id: 5, qualities: ["fast", "tiny"] }
        ]
    },
    {
        id: 30,
        cars: [
            { id: 6, qualities: ["slow", "small"] },
            { id: 7, qualities: ["offRoad", "tiny"] },
            { id: 8, qualities: ["fast", "loud"] }
        ]
    }
];

var featuresTofind = ["loud", "fast", "tiny"];

var result = garageArray.filter(function (garage) {
    var featuresFound = featuresTofind.filter(function (feature) {
        return garage.cars.some(function (car) {
            return car.qualities.includes(feature);
        });
    });
    return featuresFound.length === featuresTofind.length;
});

console.log(result);

答案 1 :(得分:2)

缺点是汽车要循环两次:-)希望还可以。

garageArray.filter(garage => {
    return garage.cars.some(car => {
        return car.qualities.includes("fast")
    }) && garage.cars.some(car => {
        return car.qualities.includes("tiny")
    });
})