Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check object equality in object array with using array includes function?

I want to check an array has the object which given as parameter to js includes function. For example:

let arr = [
    {'name': 'max', 'age': '20'},
    {'name': 'max', 'age': '21'},
    {'name': 'jane', 'age': '22'}];
console.log(arr.includes({'name': 'max', 'age': '21'})); // FALSE

That give me "false" value. How can I check object equality in object array without for loop eq.

like image 634
midstack Avatar asked Jun 07 '26 07:06

midstack


2 Answers

You can write a generic function like

let matches = flt => x => Object.keys(flt).every(k => flt[k] === x[k]);

and then

arr.some(matches({'name': 'max', 'age': '21'}))

This performs shallow, partial comparison. If you need other modes, like full and/or deep comparison, this would be far more tricky to implement. I'd suggest using lodash (_.isMatching, _.isEqual) in this case.

like image 65
georg Avatar answered Jun 10 '26 04:06

georg


You cannot do this with includes because you don't handle the equality check and the objects are different, therefore, nothing matches.

To do what you want, you can use some or find !

let arr = [
    {'name': 'max', 'age': '20'},
    {'name': 'max', 'age': '21'},
    {'name': 'jane', 'age': '22'}
];

console.log(arr.some(({name, age}) => name === 'max' && age === '21'));
console.log(!!arr.find(({name, age}) => name === 'max' && age === '21'));

Please note that find returns the object, I've added !! to print a boolean result, but that's not necessarily mandatory.

like image 28
sjahan Avatar answered Jun 10 '26 03:06

sjahan