How to check if an object with 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
    }
];
+4
source share
3 answers

You can use .somefor example

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);
Run codeHide result
+6
source

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));
Run codeHide result
0
source

You can loop through the array and check if it has the required key. Object.keysgives you an array of property names on which you can useArray.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!!");
});
0
source

All Articles