HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

From an array of objects, extract value of a property as array

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraypropertyfromextractobjectsvalue

Problem

I have JavaScript object array with the following structure:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];


I want to extract a field from each object, and get an array containing the values, for example field foo would give array [ 1, 3, 5 ].

I can do this with this trivial approach:

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 more elegant or idiomatic way to do this, so that a custom utility function would be unnecessary?

Note about suggested duplicate, it covers how to convert a single object to an array.

Solution

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);


OR

let result = objArray.map(({ foo }) => foo)


You can also check Array.prototype.map().

Code Snippets

let result = objArray.map(a => a.foo);
let result = objArray.map(({ foo }) => foo)

Context

Stack Overflow Q#19590865, score: 2659

Revisions (0)

No revisions yet.