How to find if an Object property exists in an array with Lodash.js and JavaScript?

Estimated read time 1 min read

You can use the Lodash library’s _.some() or _.find() method to check if an object property exists in an array in JavaScript. Here’s an example using _.some():

let arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'cherry'}];
let search = 2;

if (_.some(arr, ['id', search])) {
  console.log(`The array contains an object with id "${search}"`);
} else {
  console.log(`The array does not contain an object with id "${search}"`);
}

This will output The array contains an object with id "2".

And here’s an example using _.find():

let arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'cherry'}];
let search = 2;

let result = _.find(arr, ['id', search]);
if (result) {
  console.log(`The array contains an object with id "${search}"`);
} else {
  console.log(`The array does not contain an object with id "${search}"`);
}

This will also output The array contains an object with id "2".

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply