【问题标题】:How to Filter Data Name and Add The Quantity of that Filtered Data如何过滤数据名称并添加过滤数据的数量
【发布时间】: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 Red600Color Yellow添加后的数量相同600

[600, 600]

尺寸: 根据上述数据,Size Small400Size Medium200Size Large为@ 987654327@.

[400, 200, 600]

【问题讨论】:

  • 请在此处分享您的策略。您使用什么确切的算法来获得结果?
  • 你好,我只是想让每种颜色都像“红色”一样,它应该已经分类而不是硬编码。我只是想分别获得每种颜色和尺寸的总量

标签: javascript arrays object filter


【解决方案1】:

希望这段代码对你有帮助

按颜色排序:

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

【讨论】:

  • 解释代码应该做什么总是比一堆格式不正确的代码更有帮助。
  • 它可以满足我的需要,但由于我希望它是动态的而不是硬编码的,有什么办法可以删除重复而不是硬编码var color = ["Red", "Yellow"]
【解决方案2】:

这是颜色的一种方式

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

【讨论】:

  • 感谢您的回答,这正是我一直需要的,我也应用了尺寸而不是颜色,它也可以正常工作。非常感谢,已经投票并使其成为解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多