Caio Kawasaki
Caio Kawasaki

Reputation: 2950

How to check if an object with an id property exists inside an array?

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

Answers (3)

Amit Joki
Amit Joki

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

AmmarCSE
AmmarCSE

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

Oleksandr T.
Oleksandr T.

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

Related Questions