Javascript过滤器具有多个条件和值的对象数组

时间:2019-03-21 00:41:05

标签: javascript arrays reactjs object

在react / nextjs中,我正在基于带有复选框的用户输入在数据道具的前端设置过滤。

数据看起来像这样(显然更长):

[{id: 8211,
title: "ABC",
type: "hardwood",
length: "5",
width: "10",
color: "brown",
finish: "WOCA",
surface: "distressed",
},
{
id: 8208,
title: "DEF",
type: "vinyl",
length: "10",
width: "4",
color: "",
finish: "Urethane",
surface: "smooth",
}]

现在我需要按以下键/值对进行过滤:

  • 类型(硬木,wpc,spc,层压板,乙烯基)
  • 宽度(4,6)
  • 长度(6,12,24)
  • 颜色(棕色,中等,灰色,浅色)
  • 完成(沃卡,尿烷)
  • 表面(光滑,心疼,拉丝)

因此,如果有人检查硬木,乙烯基和棕色-这应该显示与硬木 OR 乙烯基 AND 和棕色相匹配的产品。

现在我不确定如何继续。我可以捕获用户输入并将其存储在一个对象中(可能使用对象内部的数组)。但是我似乎无法弄清楚如何基于此过滤我的原始道具对象。

1 个答案:

答案 0 :(得分:1)

您可以使用带有选中选项的对象,然后filter基于该对象的数据:

const data = [{
    id: 8211,
    title: "ABC",
    type: "hardwood",
    length: "5",
    width: "10",
    color: "brown",
    finish: "WOCA",
    surface: "distressed",
  },
  {
    id: 8208,
    title: "DEF",
    type: "vinyl",
    length: "10",
    width: "4",
    color: "",
    finish: "Urethane",
    surface: "smooth",
  }
];

const options = {
  color: ["brown", "randomColor"]
};

const filtered = data.filter(obj => Object.keys(options).some(key => {
  if (key != "color") {
    return obj[key] == options[key];
  } else {
    return options[key].some(s => s == obj[key]);
  }
}));

console.log(filtered);

ES5语法:

var data = [{
    id: 8211,
    title: "ABC",
    type: "hardwood",
    length: "5",
    width: "10",
    color: "brown",
    finish: "WOCA",
    surface: "distressed",
  },
  {
    id: 8208,
    title: "DEF",
    type: "vinyl",
    length: "10",
    width: "4",
    color: "",
    finish: "Urethane",
    surface: "smooth",
  }
];

var options = {
  color: "brown"
};

var filtered = data.filter(function(obj) {
  return Object.keys(options).some(function(key) {
    if (key != "color") {
      return obj[key] == options[key];
    } else {
      return options[key].some(function(s) {
        return s == obj[key];
      });
  })
});

console.log(filtered);