I have javascript object array:
objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
I want to get all values of key foo
as array [ 1, 3, 5 ]
.
There's the obvious manual way:
function getFields(input, field) {
var output = [];
for (var i=0; i < input.length ; ++i)
output.push(input[i][field]);
return output;
}
var result = getFields(objArray, "foo"); // returns [ 1, 3, 5 ]
Is there a better way? (With a reference link, if possible.)
var foos = objArray.pluck("foo");
. – Pointy Oct 25 '13 at 13:16Array.prototype.map
function where it exists – Alnitak Oct 25 '13 at 13:22