0

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}];

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

But what if I don't know keys or have another array of objects with different key names?
Can you give an example? Do the keys in the obj always exist in the keys of objects in the array?
Yes, in first example we had name, children keys in another we'd have age, height, weight or whatever (in both array and obj). So I can't use key names, I rather need a universal solution for both cases.
I think @JarekKulikowski 's answer is what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.