geochanto
geochanto

Reputation: 1002

Javascript filter Array of objects with multiple conditions and values

Working in react/nextjs, I'm setting up filtering on the front-end for data props based on user input with checkboxes.

Data looks something like this (obviously much longer):

[{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",
}]

Now I need to filter by these key/value pairs:

So if someone checks hardwood, vinyl, and brown - this should display products that match hardwood OR vinyl AND brown.

Now I'm not exactly sure how to proceed. I can capture the user input and store it in an object (possibly using arrays inside object). But I can't seem to figure out how to then filter my original props object based on that.

Upvotes: 1

Views: 3482

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44107

You can take an object with the checked options, and then filter the data based on that:

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 syntax:

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

Upvotes: 2

Related Questions