Reputation: 2950
This is my array, how can i check if an object inside it has a specific id property?
var products = [
{
id: 40,
qtd: 5
},
{
id: 32,
qtd: 2
},
{
id: 38,
qtd: 3
}
];
Upvotes: 4
Views: 118
Reputation: 59232
You can loop through the array and check if it has the required key. Object.keys
gives you an array of property names, on which you can use Array.indexOf
arr.forEach(function(obj){
var prop_name = "id"
if(Object.keys(obj).indexOf(prop_name) > -1)
alert("Property present!");
else
alert("Property is missing!!");
});
Upvotes: 0
Reputation: 30557
var id = 40;
var products = [
{
id: 40,
qtd: 5
},
{
id: 32,
qtd: 2
},
{
id: 38,
qtd: 3
}
];
function findId(needle, haystack){
for(var i = 0; i < haystack.length; i++){
if(haystack[i].id == needle){
return haystack[i];
}
}
return false;
}
console.log(findId(id, products));
Upvotes: 0
Reputation: 77482
You can use .some
, like so
var products = [
{
id: 40,
qtd: 5
},
{
id: 32,
qtd: 2
},
{
id: 38,
qtd: 3
}
];
var id = 40;
var isExist = products.some(function (el) {
return el.id === id;
});
console.log(isExist);
Upvotes: 6