javascript - 如何过滤数据名称并添加过滤数据的数量
问题描述
我正在尝试创建一个数据,如果颜色和大小相同,则在其中添加数字。为了说明我的意思,下面是我的代码。
代码
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
,中号是200
,大号是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);
推荐阅读
- nginx - nextcloud 的 Nginx 反向代理不起作用
- jwt - 如何通过 Cookie 撤销 JWT 身份验证?
- scala - Spark 中的循环分区如何工作?
- reactjs - 在 React Bootstrap 对话框中,如果对话框的主体内部有一个组件,如何引用组件及其状态?
- python - try-except 后“else”块的目的是什么?
- wordpress - Apache 子域重定向到 www 上的 WordPress
- javascript - 如何在 Facebook 等我的项目中创建和表情符号?
- python - 使用 python 读取 MYSQL Db 会返回一个元组,我需要将其转换为列表
- code-signing-certificate - 代码签名证书过期后,已经安装的应用程序会发生什么?
- arrays - 在非常大的数组中计算较小或相等元素的更快方法?