4

I have an array like this:

[
  {foo: 1, bar: 2},
  {foo: 3, bar: 4}
]

What's the most concise and ES6-way of getting an array of only the foo values?

Expected result would be:

[1, 3]
Juicy
  • 11,840
  • 35
  • 123
  • 212

4 Answers4

8

Use the .map() method to loop through the items.

Simply put:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

- MDN web docs

The method allows to call the provided callback function once for each element of the array. It creates a new array made of the mapped elements. You can pass both the element and index as arguments of the callback. The latter is optional (when you don't need it in the callback).

It's a clean way of accessing objects in JavaScript. Here is the code:

let array = [
  {foo: 1, bar: 2},
  {foo: 3, bar: 4}
]

console.log(array.map( e => e.foo ))
Community
  • 1
  • 1
Ivan
  • 34,531
  • 8
  • 55
  • 100
1

The Array.prototype.map method is suitable for mapping/transforming one array into another array of the same size. You pass in a function which transforms from one element in the array to a new one. As of 2018 it is considered "modern" to use the so called fat arrow syntax to define an anonymous function for the transformation:

const x = [{foo: 1, bar: 2}, {foo: 3, bar: 4}]
x.map(entry => entry.foo)

It is also considered "modern" to try to avoid the writing of for loops.

lipp
  • 5,586
  • 1
  • 21
  • 32
  • 2
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Luca Kiebel May 29 '18 at 20:00
1

You could use a destructuring assignment and return this property by using Array#map.

var objects = [{ foo: 1, bar: 2 }, { foo: 3, bar: 4 }],
    array = objects.map(({ foo }) => foo);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Expanding lipp's answer:

const x = [{foo: 1, bar: 2}, {foo: 3, bar: 4}];
var y = x.map(entry => entry.foo);

In the first line, an array of objects is created. The second line uses a minified lambda expression to return an array of foo attributes from the x array and assign it to y.

Diego Victor de Jesus
  • 2,575
  • 2
  • 19
  • 30