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]
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]
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.
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 ))
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.
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);
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.