Accessing properties of an array of objects

前端 未结 5 1740
遇见更好的自我
遇见更好的自我 2020-12-09 05:35

pretty basic question I think, but I couldn\'t find info on that.

Through d3 I parse a csv and each object look like this

name: \"whatever\"
number:          


        
相关标签:
5条回答
  • 2020-12-09 06:18

    If you are using lodash, you can do this:

    var numbers = _.map(originalArray, 'number')

    0 讨论(0)
  • 2020-12-09 06:27
    for (i=0; i<myArrayOfObjects.length; i++) {
        doWhatever(myArrayOfObjects[i].number);
    }
    
    0 讨论(0)
  • 2020-12-09 06:37

    Use array.map:

    var numbers = objects.map(function(o) { return o.number; });
    
    0 讨论(0)
  • 2020-12-09 06:42

    ES6 version:

    const numbers = objects.map( o => o.number );
    

    Enjoy.

    0 讨论(0)
  • 2020-12-09 06:42

    In JavaScript, you can't, because there is no such array. If you've got an array of objects, well, each object is its own precious little snowflake. You can of course transfer the "number" values to a new array, but it'd definitely be a new array.

    Some toolkits (Prototype and maybe Functional and Underscore) have a "pluck()" facility that's designed to do exactly what you want, but they too are forced to create new arrays.

    function pluck(array, property) {
      var i, rv = [];
    
      for (i = 0; i < array.length; ++i) {
        rv[i] = array[i][property];
      }
    
      return rv;
    }
    

    Then:

    var arrayOfNumbers = pluck(originalArray, "number");
    
    0 讨论(0)
提交回复
热议问题