【发布时间】:2021-10-29 05:25:59
【问题描述】:
我正在尝试创建一个数据,如果颜色和大小相同,则在其中添加数字。为了说明我的意思,下面是我的代码。
代码
const data = [
{
id: 1,
name: "Product A",
attributes: [
{
color: "Red",
size: "Small",
qty: 200,
},
{
color: "Red",
size: "Medium",
qty: 100,
},
{
color: "Red",
size: "Large",
qty: 300,
},
{
color: "Yellow",
size: "Small",
qty: 200,
},
{
color: "Yellow",
size: "Medium",
qty: 100,
},
{
color: "Yellow",
size: "Large",
qty: 300,
},
],
},
];
const attributeList = data.flatMap(({ attributes }) => {
return attributes.map((item) => {
return item.color;
});
});
console.log(attributeList);
例如,我的目标是看起来像这样的结果。
颜色:
根据上述数据,Color Red为600,Color Yellow添加后的数量相同600。
[600, 600]
尺寸:
根据上述数据,Size Small为400,Size Medium为200,Size Large为@ 987654327@.
[400, 200, 600]
【问题讨论】:
-
请在此处分享您的策略。您使用什么确切的算法来获得结果?
-
你好,我只是想让每种颜色都像“红色”一样,它应该已经分类而不是硬编码。我只是想分别获得每种颜色和尺寸的总量
标签: javascript arrays object filter