Get JavaScript object from array of objects by value of property

This question already has an answer here:

  • Find object by id in an array of JavaScript objects 28 answers

  • var result = jsObjects.filter(function( obj ) {
      return obj.b == 6;
    });
    

    查看Array.prototype.filter()上的MDN Docs


    jsObjects.find(x => x.b === 6)
    

    From MDN:

    The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


    Side note: methods like find() and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel.


    I don't know why you are against a for loop (presumably you meant a for loop, not specifically for..in), they are fast and easy to read. Anyhow, here's some options.

    For loop:

    function getByValue(arr, value) {
    
      for (var i=0, iLen=arr.length; i<iLen; i++) {
    
        if (arr[i].b == value) return arr[i];
      }
    }
    

    .filter

    function getByValue2(arr, value) {
    
      var result  = arr.filter(function(o){return o.b == value;} );
    
      return result? result[0] : null; // or undefined
    
    }
    

    .forEach

    function getByValue3(arr, value) {
    
      var result = [];
    
      arr.forEach(function(o){if (o.b == value) result.push(o);} );
    
      return result? result[0] : null; // or undefined
    
    }
    

    If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check. eg

    function getByValue4(arr, value) {
      var o;
    
      for (var i=0, iLen=arr.length; i<iLen; i++) {
        o = arr[i];
    
        for (var p in o) {
          if (o.hasOwnProperty(p) && o[p] == value) {
            return o;
          }
        }
      }
    }
    
    链接地址: http://www.djcxy.com/p/27226.html

    上一篇: 访问/进程(嵌套)对象,数组或JSON

    下一篇: 通过属性值从对象数组中获取JavaScript对象