【问题标题】:Search through Object Array in Javascript [duplicate]在Javascript中搜索对象数组[重复]
【发布时间】:2016-10-07 15:07:18
【问题描述】:

我有一个包含对象的 javascript 数组:

var array;
array[{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];

如何判断这个数组中是否有名字 Peter?

编辑:我想要这样的东西

if (array.find("Peter"))
{
  ...
}

【问题讨论】:

  • 通过遍历数组

标签: javascript html arrays object


【解决方案1】:

使用find

arr.find(row => row.name === 'Peter');

如果您的目标浏览器不支持此方法,请不要忘记在链接中使用 polyfill。

【讨论】:

    【解决方案2】:
    var array = [{name: "Peter",class: "7"},
                 {name: "Klaus",class: "3"}];
    
    var filtered = array.filter(function(item){
        return item.name == 'Peter';
    });
    
    // filtered now equals [{name: "Peter",class: "7"}]
    

    【讨论】:

    • 不错的解决方案!我总是看到迭代解决方案。
    【解决方案3】:

    首先你应该更正你的数组声明

    var array = [{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];
    

    你应该试试

    array.find(function(o) { return o.name==="Klaus" })
    

    希望得到帮助:-)

    【讨论】:

      【解决方案4】:
      var students = [{name: "Peter", class: "7"}, {name: "Klaus", class: "3"}];
      students.find( student => { return student.name === 'Peter' });
      
      function find(arr, key, value) {
          return arr.find( item => {
              return item[key] === value;
          }) !== undefined;
      }
      
      
      console.log(find(students, 'name', 'Peter'));
      

      【讨论】:

        【解决方案5】:

        ES6 和 ES5 中的一些示例代码!

        // Search for "Peter" in the name field
        if (arr.find(row => row.name === 'Peter')) {
            console.log('found');
        } else {
            console.log('not found');
        }
        
        // Same function in ES5
        arr.find(function(row) {
            console.log(row);
            if (row.name === 'Peter') {
            console.log('ES5: found');
          }
        });
        

        【讨论】:

          【解决方案6】:
          array.findIndex(e => e['name'] === 'Peter')
          

          AngularJS 解决方案之一

          【讨论】:

            猜你喜欢
            • 2018-03-25
            • 1970-01-01
            • 1970-01-01
            • 2015-05-18
            • 2011-04-07
            • 2013-09-08
            • 2013-10-27
            • 2019-02-12
            • 1970-01-01
            相关资源
            最近更新 更多