简体   繁体   English

在 JavaScript 中检查数组是否包含具有特定属性值的对象?

[英]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"?如何从该数组中删除名称设置为“zipCode”的对象?

If you need to modify the existing Array, you should use splice() .如果需要修改现有数组,则应使用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.这是为了处理这样一个事实,即当您执行.splice(i, 1) ,数组将被重新索引。

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.如果我们执行前向循环,我们还需要在执行.splice()时调整i以避免跳过索引。

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"检查每个项目的名称,如果它是“zipCode”
    • If it is, splice it off using yourArray.splice(index,1) ;如果是,请使用yourArray.splice(index,1)其拼接起来;

Then either:然后:

  • continue if there is a possibility of having more than one name having the value "zipCode"如果可能有多个名称的值为“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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查数组是否包含具有特定属性值的对象 - Check if array contains an object with the value of a specific property JSON / Javascript:返回哪个数组对象包含某个属性 - JSON/Javascript: return which array object contains a certain property JavaScript / jQuery检查数组是否包含所有特定值? - JavaScript/jQuery check that array contains all a certain value? 如何检查数组是否包含值,这是对象的属性? - How to check if array contains value, which is a property of an an object? 检查对象数组中的每个 object 是否包含另一个数组中的值(JavaScript) - Check if each object in array of objects contains a value that is in another array (JavaScript) JavaScript - 如果 object 属性具有特定值,则创建一个 object 键数组 - JavaScript - Create an array of object keys if the object property has certain value 检查对象是否包含值javascript - check if object contains value javascript 使用javascript获取属性包含数组的对象作为值 - get the object which property contains an array as the value using javascript JavaScript / VueJS:检查数组是否包含具有特定值的元素的对象 - JavaScript/VueJS: Check if an Array contains an object with an element that has specific value 如何检查Javascript对象是否包含数组作为属性值? - How to check if a Javascript object contains an array as a value for an attribute?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM