Reputation: 22580
I am trying to check whether an object with a certain id property is already present in the array:
var items =[{id:1,name:'ted'},{id:2,name:'john'}]
How can I do this with jquery or vanilla js in a compact way? I know I can just create a for loop but is there anything else you can use?
Upvotes: 1
Views: 80
Reputation: 1
var items =[{id:1,name:'ted'},{id:2,name:'john'},{id:3, name:'tod'}];
var id = 2;
var checkid = false;
for(var i =0; i<items.length; i++){
if(items[i].id ==id) //this condition check if id exists or not)
checkid=true;
}
Upvotes: 0
Reputation: 13356
Use array.prototype.some:
var items =[{id:1,name:'ted'},{id:2,name:'john'},{id:3, name:'tod'}];
var id = 2;
var exists = items.some(item => item.id === id)
console.log(exists);
Upvotes: 3