Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 846
hyde Avatar asked Oct 25 '13 13:10

hyde


People also ask

How do you convert the values of an object into an array?

You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How do I extract an array from an array?

Double-click Extract Elements from Arrays in the Tasks list. Draw a connector between an array input node, and the Extract Elements from arrays node. Examples of array input include an Array of Values node or a task that produces an array. Click the button in the Extract Elements from Array node.

How do you access the properties of an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };


2 Answers

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().

like image 102
Jalasem Avatar answered Oct 21 '22 21:10

Jalasem


Yes, but it relies on an ES5 feature of JavaScript. This means it will not work in IE8 or older.

var result = objArray.map(function(a) {return a.foo;}); 

On ES6 compatible JS interpreters you can use an arrow function for brevity:

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

Array.prototype.map documentation

like image 32
Niet the Dark Absol Avatar answered Oct 21 '22 22:10

Niet the Dark Absol