1

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

6
  • I need it to return true if it is else false Commented Jan 18, 2021 at 16:50
  • stackoverflow.com/questions/12462318/… Commented Jan 18, 2021 at 16:51
  • 1
    Does this answer your question? Find a value in an array of objects in Javascript Commented Jan 18, 2021 at 16:51
  • That answer returns the entire object or undefined but I just need a true or false Commented Jan 18, 2021 at 16:53
  • 2
    Array#some() returns boolean Commented Jan 18, 2021 at 16:53

2 Answers 2

8

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

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

Comments

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

1 Comment

Using some() or find() is more efficient since they break when condition met and don't require generating a new array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.