【问题标题】:Check if an array contains an object with a certain property value in JavaScript?在 JavaScript 中检查数组是否包含具有特定属性值的对象?
【发布时间】:2012-10-31 14:43:45
【问题描述】:

如果我有类似的东西

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

我如何删除从该数组中名称设置为“zipCode”的对象?

【问题讨论】:

  • 应该正确写成:[{id: 03235252, name: "streetAddress"}, {id: 32624666, name: "zipCode"}]

标签: javascript arrays object


【解决方案1】:

如果你需要修改现有的Array,你应该使用splice()

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

请注意,我正在反向循环。这是为了处理当您执行.splice(i, 1) 时,数组将被重新索引。

如果我们执行前向循环,我们还需要在执行.splice() 时调整i 以避免跳过索引。

【讨论】:

    【解决方案2】:
    arr = arr.filter(function (item) {
      return (item.name !== 'zipCode');
    });
    

    【讨论】:

    • 可能值得一提的是它doesn't work in IE 8所以你可能不得不shim它。
    • 应该注意这不会从数组中删除对象。它构建一个新数组并替换旧数组,如果有多个对同一个数组的引用,这可能是一个问题。
    【解决方案3】:
    var i = array.length;
    while(i-- > 0) {
        if (array[i].name === "zipCode")
            array.splice(i, 1);
    }
    
    • 向后循环遍历数组(因此拼接时不必跳过索引)
    • 检查每个项目的名称,如果它是“邮政编码”
      • 如果是,使用yourArray.splice(index,1)拼接;

    然后:

    • 如果可能有多个名称的值“zipCode”,请继续
    • 打破循环

    【讨论】:

      【解决方案4】:

      更新建议

      更新了这个答案,因为在数组上做原型是不好的做法,所以让使用这个建议的人在这里编写更好的代码是一个更好的选择:

      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)
      
      // Could also be simply written like this:
      const otherArr = myArr.filter(item => item.name !== 'jimmy')
      

      新代码可以找到并测试here

      老建议

      这也可以通过数组上的原型来完成

      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
      

      代码也可以找到并测试here

      【讨论】:

        【解决方案5】:

        这可能是一个详细而简单的解决方案。

        //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
        }
        

        【讨论】:

          猜你喜欢
          • 2017-02-08
          • 1970-01-01
          • 2012-02-02
          • 2016-04-21
          • 2023-03-26
          • 1970-01-01
          • 2012-11-12
          • 2010-09-13
          相关资源
          最近更新 更多