How to extract value of a property as an array from an array of objects in Javascript?
Question
There is an object array:1
objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
How to extract the values of key foo
into an arrya like [1, 3, 5]
?
Answer
ES 6
By using map
and =>
function can easily make it happen.1
var result = objArray.map(a => a.foo);
ES 5
Since ES 5 doesn’t support =>
, so we need a function to get the value.1
var result = objArray.map(function(a) {return a.foo;});
Reference
This is the end of post