gpt4 book ai didi

javascript - 过滤对象数组,其中子项必须匹配所有条件

转载 作者:行者123 更新时间:2023-11-28 14:30:45 25 4
gpt4 key购买 nike

我需要解析带有嵌入对象数组的对象数组,我知道我可以使用 .filter() 来完成。但是我需要检查嵌入数组是否至少具有多种类型的对象之一。请参阅下面的示例:

我有一个车库对象数组,其中有一个“汽车”字段,它是一个汽车数组。每辆车都是具有多种品质的物体。我需要查看哪些车库至少拥有一辆“快速”汽车和至少一辆“小型”汽车。如果这两种品质属于同一辆车也没关系。在 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 的车库。

最佳答案

这应该可以做到:

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

关于javascript - 过滤对象数组,其中子项必须匹配所有条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51640111/

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