简体   繁体   中英

Check if an array contains an object with a certain 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 that array that has name set to "zipCode"?

If you need to modify the existing Array, you should use splice() .

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

Notice that I'm looping in reverse. This is in order to deal with the fact that when you do a .splice(i, 1) , the array will be reindexed.

If we did a forward loop, we would also need to adjust i whenever we do a .splice() in order to avoid skipping an index.

arr = arr.filter(function (item) {
  return (item.name !== 'zipCode');
});
var i = array.length;
while(i-- > 0) {
    if (array[i].name === "zipCode")
        array.splice(i, 1);
}
  • Loop through the array backwards (so you won't have to skip indexes when splicing)
  • Check each item's name if it's "zipCode"
    • If it is, splice it off using yourArray.splice(index,1) ;

Then either:

  • continue if there is a possibility of having more than one name having the value "zipCode"
  • break the loop

Updated suggestion

Updated this answer due to doing prototypes on arrays are bad prac so to get people who use the suggestion to write better code here is a better option:

const myArr = [
  {
    name: "lars",
    age: 25
  }, {
    name: "hugo",
    age: 28
  }, {
    name: "bent",
    age: 24
  }, {
    name: "jimmy",
    age: 22
  }
];

const findAndRemove = (array, prop, value) => {
  return array.filter((item) => item[prop] !== value);
}

const newArr = findAndRemove(myArr, 'name', 'jimmy')

console.log(newArr)

New code can be found and tested here

Old suggestion

This can also be done with a prototype on the 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
 
 
 

Code can also be found and tested here

This may be a detailed and easy solution.

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
   // value exists in array
   //write some codes
}

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}
  ];

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
{
   // returns true
   // object exists in array
   //write some codes
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM