Anand Somani
Anand Somani

Reputation: 801

Filtering Data using Properties values using ES6

Like to filter data based on properties values from Object Let's say I have an object:

{
  A: { value1: 4, value2: 2, value3: 5 },
  B: { value1: 2, value2: 5, value3: 8 },
  ...
}

I want to create object by filtering the object above so I have something like if I filter based on value1: 4 and value2: 2

{
  value1: 4,
  value2: 2,
  value3: 5
}

I am looking for a clean way to accomplish this using Es6.

Upvotes: 0

Views: 67

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28434

const 
  obj = { A: { value1: 4, value2: 2, value3: 5 }, B: { value1: 2, value2: 5, value3: 8 } },
  filter = { value1: 4, value2: 2 };

// get key-value pairs of filter  
const filterPairs = Object.entries(filter);
  
// iterate over obj's values, and return the ones matching filterPairs
const matches = 
  Object.values(obj)
  .filter(o => filterPairs.every(([key, value]) => o[key] === value));
  
console.log(matches);

Note: if you only want to get the first matching object, use Array#find instead of Array#filter

Upvotes: 1

Related Questions