How to find an appropriate object in array by one of its properties

后端 未结 3 1705
后悔当初
后悔当初 2020-12-04 04:11

Say, I have that simple array of objects.

var x = [
            {
                id:      1001
                name:    \"Jim\",
                surname: \"         


        
相关标签:
3条回答
  • 2020-12-04 04:23

    A simple loop will suffice:

    for(var i=0, len=x.length; i < len; i++){
        if( x[i].id === 1002){
            //do something with x[i]
        }
    }
    

    Even though you are dealing with json remember that it's all just a hierarchy of arrays, objects and primitives.

    0 讨论(0)
  • 2020-12-04 04:27

    As of ES2015, JavaScript arrays have find and findIndex methods, both of which are easily polyfilled (see those MDN links for polyfills).

    In your case, you'd use find:

    var found = x.find(function(entry) { return entry.id == 1002; });
    

    or also using other (non-polyfillable) ES2015 features:

    const found = x.find(entry => entry.id == 1002);
    
    0 讨论(0)
  • 2020-12-04 04:45

    The easiest way is to define a find function which takes a predicate

    function find(arr, predicate) { 
      for (var i = 0; i < arr.length; i++) {
        if (predicate(arr[i]) {
          return arr[i];
        }
      }
      return null;
    }
    

    Then you can just use this method on the array

    var found = find(x, function (item) { item.id === 1002 });
    
    0 讨论(0)
提交回复
热议问题