Check if an array contains an object with a specific property value in JavaScript?

If I have something like

[Object(id:03235252, name:"streetAddress"), Object(id:32624666, name:"zipCode")...] 

How can I remove an object from this array with the name set to "zipCode"?

+7
source share
4 answers

If you need to modify an existing array, you should use splice() .

 for (var i = array.length - 1; i > -1; i--) { if (array[i].name === "zipCode") array.splice(i, 1); } 

Note that I loop in the reverse order. This is necessary in order to cope with the fact that when executing .splice(i, 1) array will be re-indexed.

If we did a direct loop, we would also need to adjust i whenever we do .splice() to avoid skipping the index.

+11
source
 arr = arr.filter(function (item) { return (item.name !== 'zipCode'); }); 
+8
source
 var i = array.length; while(i-- > 0) { if (array[i].name === "zipCode") array.splice(i, 1); } 
  • Scroll the array back (so you don't have to skip indices when splicing)
  • Check the name of each item if it is "zipCode"
    • If so, join it using yourArray.splice(index,1) ;

Then either:

  • continue if it is possible to have more than one name with a value of "zipCode"
  • cycle break
+2
source

This can also be done using a prototype array.

 Array.prototype.containsByProp = function(propName, value){ for (var i = this.length - 1; i > -1; i--) { var propObj = this[i]; if(propObj[propName] === value) { return true; } } return false; } var myArr = [ { name: "lars", age: 25 }, { name: "hugo", age: 28 }, { name: "bent", age: 24 }, { name: "jimmy", age: 22 } ]; console.log(myArr.containsByProp("name", "brent")); // Returns false console.log(myArr.containsByProp("name", "bent")); // Returns true 

The code can also be found and tested here.

+1
source

All Articles