0

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.

Tom Foster
  • 462
  • 2
  • 10
Anand Somani
  • 801
  • 1
  • 6
  • 15
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 15 '21 at 21:02
  • @SebastianSimon I don't have reference of A, I don't want to send A while filtering data. – Anand Somani Sep 15 '21 at 21:05

1 Answers1

1

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

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48