javascript - 使用对象键动态过滤数组
问题描述
我正在尝试过滤一个数组,例如我希望它返回所有颜色、大小等,我知道你可以通过执行以下操作来过滤它:
const products = [
{
name: "Product A",
attributes: [
{
color: "Yellow",
size: "Small",
price: 100,
quantity: 30,
},
{
color: "Yellow",
size: "Medium",
price: 150,
quantity: 20,
},
{
color: "Yellow",
size: "Large",
price: 200,
quantity: 10,
},
{
color: "Red",
size: "Small",
price: 100,
quantity: 15,
},
{
color: "Red",
size: "Medium",
price: 150,
quantity: 10,
},
{
color: "Red",
size: "Large",
price: 200,
quantity: 5,
},
{
color: "Blue",
size: "Small",
price: 100,
quantity: 15,
},
{
color: "Blue",
size: "Medium",
price: 150,
quantity: 10,
},
{
color: "Blue",
size: "Large",
price: 200,
quantity: 5,
},
],
},
];
const result = data.map(({ attributes }) =>
attributes.filter(({ color }) => color === "Red")
);.
console.log(result)
但是如果有 100 个属性颜色和大小怎么办,如果黄色数组将返回所有黄色数据,如何通过颜色样本将它们分开?
[
{
color: "Yellow",
size: "Small",
price: 100,
quantity: 30,
},
{
color: "Yellow",
size: "Medium",
price: 150,
quantity: 20,
},
{
color: "Yellow",
size: "Large",
price: 200,
quantity: 10,
},
]
对于尺寸,它将返回例如 small 它将返回所有小数据,如下所示:
[{
color: "Yellow",
size: "Small",
price: 100,
quantity: 30,
},
{
color: "Red",
size: "Small",
price: 100,
quantity: 15,
},
{
color: "Blue",
size: "Small",
price: 100,
quantity: 15,
}]
如果我的问题不是很清楚,请告诉我,以便我澄清,谢谢你的帮助
解决方案
这与问题的格式并不真正匹配,但它是一个有效的答案。
const array = [
{
color: "red",
size: "small"
},
{
color: "yellow",
size: "small"
},
{
color: "red",
size: "large"
}
];
function sortArrayByItemProperties(array, ...properties) {
const map = {};
for(let i = 0; i < properties.length; i++) {
const property = properties[i];
map[property] = {};
for(let ii = 0; ii < array.length; ii++) {
const object = array[ii];
if(!map[property][object[property]]) map[property][object[property]] = [];
map[property][object[property]].push(object);
}
}
return map;
}
console.log(JSON.stringify(sortArrayByItemProperties(array, "color", "size")));
推荐阅读
- javascript - TypeError:AWS.Location 不是构造函数
- django - 其中哪个是 django 中最昂贵的查询?
- api - 来自多个不同 REST 调用的数据的有序分页
- angular - Ionic Angular 应用程序无法在 Xcode 12.5 MacOS 11.5.2 中引导 - 已解决
- json - 如何通过在flutter中调用API动态添加行元素?
- python - 缩短冗余计算
- mongodb - 将 mongodb 集合导出到 csv
- r - 如何解决这个错误:错误:美学必须是长度1或与数据相同(1):标签,x,y,颜色和组
- android - Android 12 模拟器中的 Google Chrome 浏览器不加载任何网页(互联网正在运行!)
- python - 在 SchemaRegistryClient Confluent Kafka 中禁用证书验证