首页 > 解决方案 > 使用对象键动态过滤数组

问题描述

我正在尝试过滤一个数组,例如我希望它返回所有颜色、大小等,我知道你可以通过执行以下操作来过滤它:

const products = [
  {
    name: "Product A",
    attributes: [
      {
        color: "Yellow",
        size: "Small",
        price: 100,
        quantity: 30,
      },
      {
        color: "Yellow",
        size: "Medium",
        price: 150,
        quantity: 20,
      },
      {
        color: "Yellow",
        size: "Large",
        price: 200,
        quantity: 10,
      },
      {
        color: "Red",
        size: "Small",
        price: 100,
        quantity: 15,
      },
      {
        color: "Red",
        size: "Medium",
        price: 150,
        quantity: 10,
      },
      {
        color: "Red",
        size: "Large",
        price: 200,
        quantity: 5,
      },
      {
        color: "Blue",
        size: "Small",
        price: 100,
        quantity: 15,
      },
      {
        color: "Blue",
        size: "Medium",
        price: 150,
        quantity: 10,
      },
      {
        color: "Blue",
        size: "Large",
        price: 200,
        quantity: 5,
      },
    ],
  },
];

const result = data.map(({ attributes }) =>
    attributes.filter(({ color }) => color === "Red")
  );. 

console.log(result)

但是如果有 100 个属性颜色和大小怎么办,如果黄色数组将返回所有黄色数据,如何通过颜色样本将它们分开?

[
      {
        color: "Yellow",
        size: "Small",
        price: 100,
        quantity: 30,
      },
      {
        color: "Yellow",
        size: "Medium",
        price: 150,
        quantity: 20,
      },
      {
        color: "Yellow",
        size: "Large",
        price: 200,
        quantity: 10,
      },
]

对于尺寸,它将返回例如 small 它将返回所有小数据,如下所示:

[{
    color: "Yellow",
    size: "Small",
    price: 100,
    quantity: 30,
  },
  {
    color: "Red",
    size: "Small",
    price: 100,
    quantity: 15,
  },
  {
    color: "Blue",
    size: "Small",
    price: 100,
    quantity: 15,
  }]

如果我的问题不是很清楚,请告诉我,以便我澄清,谢谢你的帮助

标签: javascriptarraysobjectfilter

解决方案


这与问题的格式并不真正匹配,但它是一个有效的答案。

const array = [
  {
    color: "red",
    size: "small"
  },
  {
    color: "yellow",
    size: "small"
  },
  {
    color: "red",
    size: "large"
  }
];

function sortArrayByItemProperties(array, ...properties) {
  const map = {};
  for(let i = 0; i < properties.length; i++) {
    const property = properties[i];
    map[property] = {};
    for(let ii = 0; ii < array.length; ii++) {
      const object = array[ii];
      if(!map[property][object[property]]) map[property][object[property]] = [];
      map[property][object[property]].push(object);
    }
  }
  return map;
}

console.log(JSON.stringify(sortArrayByItemProperties(array, "color", "size")));


推荐阅读