14

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: "52"

How can I access the array of all the properties "number" as an array without creating a new array and pushing each element?

altocumulus
  • 21,179
  • 13
  • 61
  • 84
Dave
  • 613
  • 2
  • 5
  • 19
  • 1
    Do you mean each object looks like: `{"name":"whatever","number":52}` and you have an array of these objects? – Jonathan M Nov 26 '11 at 21:41
  • you would directly have access to the number field. just use something[i]["number"] or something[i].number ... even looping through is possible . Is there any other specific reason for you to have it as a separate array rather than accessing it directly through a way mentioned earlier...?? – Boopathi Rajaa Nov 26 '11 at 21:42

5 Answers5

31

Use array.map:

var numbers = objects.map(function(o) { return o.number; });
mbostock
  • 51,423
  • 13
  • 175
  • 129
4

ES6 version:

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

Enjoy.

Francois Nadeau
  • 7,023
  • 2
  • 49
  • 58
2

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");
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Perhaps worth enhancing `pluck` to accept a callback that is invoked in the loop and receives the value of the given property of each object. The array could still be used to return an array of values returned from the callback. – RightSaidFred Nov 26 '11 at 21:53
  • Funny, @RightSaidFred, I was just thinking that :-) Then I realized that that function would really be what you'd normally call "map()", and you could certainly implement "pluck()" in terms of "map()". – Pointy Nov 26 '11 at 21:56
  • Very true. It's just a less flexible map! Duh!! – RightSaidFred Nov 26 '11 at 21:58
1
for (i=0; i<myArrayOfObjects.length; i++) {
    doWhatever(myArrayOfObjects[i].number);
}
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
0

If you are using lodash, you can do this:

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

Colo Ghidini
  • 658
  • 9
  • 20