I J
I J

Reputation: 25

How to find all matching keys and values of one object in array of objects?

I need a code which would loop through an array of objects and check if keys and values match with ones in a separate object, and then push object that contains all keys and values in a new array, so for a specific case:

var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

result would be:

arr2 = [{name: 'john', lastname: 'roberts', children: 3}];

Upvotes: 0

Views: 166

Answers (2)

Jarek Kulikowski
Jarek Kulikowski

Reputation: 1389

expanding @Psidom version

var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

console.log(
  arr.filter(x => Object.keys(obj).every( k => x[k] == obj[k]))
);

Upvotes: 2

akuiper
akuiper

Reputation: 214927

Use filter on the Array:

var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

console.log(
  arr.filter(x => x.name === obj.name && x.children === obj.children)
);

Upvotes: 1

Related Questions