如何筛选数据名称并添加已筛选数据的数量



我正在尝试创建一个数据,如果颜色和大小相同,则会在其中添加数字。为了说明我的意思,下面是我的代码。

代码

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

例如,我的目标是取得这样的结果。

对于颜色:根据上述数据,颜色红色600,而黄色添加时为相同数量的600

[600, 600]

尺寸:根据上述数据,小尺寸400,而中尺寸尺寸600

[400, 200, 600]

这是彩色的一种方法

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 }) => {
let qt = {
color: {}
}
let color = [];
attributes.map((item) => {

if (qt.color.hasOwnProperty(item.color)){
qt.color[item.color] += item.qty
}
else {qt.color[item.color] = item.qty;}
});
for(let val in qt.color){
color.push(qt.color[val])
}
return color
});
console.log(attributeList);

我希望这段代码能帮助你

按颜色排序:

var color = ["Red","Yellow"]
data.map(o=>color.map(v=>o.attributes.reduce((sum,prev)=>prev.color === v?sum+prev.qty: sum,0)))

按大小排序:

var size = ["Small","Medium","Yellow"]
data.map(o=>size.map(v=>o.attributes.reduce((sum,prev)=>prev.color === v?sum+prev.qty: sum,0
)))

最新更新