【发布时间】:2021-07-29 16:29:03
【问题描述】:
我正在尝试过滤一个数组,例如我希望它返回所有颜色、大小等,我知道您可以通过执行以下操作来过滤它:
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,
}]
如果我的问题不是很清楚,请告诉我,以便我澄清,感谢您的帮助
【问题讨论】:
-
嗨@epascarello 感谢您的评论,您可以为我的问题提供任何示例吗?
-
您在这里真正要问的不是很清楚。如果您询问如何过滤,请参阅these answers。如果您询问如何使用变量动态访问对象属性(例如,
"size"与"color"),请参阅 these answers。 (他们也一起玩。) -
products.attributes.filter(item => item.color === "Blue") -
嗨@T.J.Crowder 我有一个想法感谢您的评论
标签: javascript arrays object filter