首页 > 解决方案 > 如何过滤数据名称并添加过滤数据的数量

问题描述

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

代码

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]

标签: javascriptarraysobjectfilter

解决方案


这是颜色的一种方式

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


推荐阅读