0

I have a single id and I need to check if it is in an array of objects. Example,

id = 2;

const arr = [{id: 1, name: 'James'}, {id: 2, name: 'Peter'}, {id: 3, name: 'Mike'}]

is there a javascript function that does this? I cant find one online the includes() method only compares if the object is in the array not if there is a property in an object exists

hernandeΩ
  • 69
  • 1
  • 2
  • 8

2 Answers2

3

let id = 3;
const arr = [{
  id: 1,
  name: 'James'
}, {
  id: 2,
  name: 'Peter'
}, {
  id: 3,
  name: 'Mike'
}]

var chek = arr.find(c => c.id === id);

console.log(chek ?? "Not present")
//or:
if (chek === undefined) {
  console.log("Not present")
} else {
  console.log(chek.name)
}

When should I use ?? (nullish coalescing) vs || (logical OR)?

ikiK
  • 6,328
  • 4
  • 20
  • 40
1

Thanks to charlietfl for pointing out that find() is more efficient than filter() if you only care that a match exists and don't need each matching instance.

You can use the find() method to check for the existance of an element that matches your conditions. If an element is not found, the containsId variable will be undefined.

var id = 2;
const arr = [{id: 1, name: 'James'}, {id: 2, name: 'Peter'}, {id: 3, name: 'Mike'}];

// Find the first element in the array
// whose id is equal to 2.
var containsId = arr.find(x => x.id === id);

// Log (or return) whether or not we found
// an element.
console.log(containsId !== undefined);
D M
  • 5,769
  • 4
  • 12
  • 27
  • 1
    Using some() or find() is more efficient since they break when condition met and don't require generating a new array – charlietfl Jan 18 '21 at 16:55