-3

I have an array of objects, similar to this:

fruits = [
  { name: apple, color: red }, {name: lemon, color: yellow } etc.
]

I'm trying to use map to get a new array of just the colors, such as

fruitColors = ['red', 'yellow']

I'm kinda new to ES6, what's the syntax for this?

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Steve
  • 14,401
  • 35
  • 125
  • 230
  • 3
    This is not ES6 specific - it's just invoking [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – VLAZ Aug 01 '19 at 14:19

4 Answers4

3

const fruits = [
  { name: 'apple', color: 'red' }, 
  { name: 'lemon', color: 'yellow' }
];

console.log(fruits.map(fruit => fruit.color));

// OR EVEN SHORTER USING DESTRUCTURING
console.log('USING DESTRUCTURING');
console.log(fruits.map(({color}) => color));
Andriy
  • 14,781
  • 4
  • 46
  • 50
1

You can just return the .color property from the map:

const fruitColors = fruits.map(f => f.color);

Also using lodash or underscore you can achieve the same by:

const fruitColors = _.map(fruits, 'color');
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
1

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

So, basically it goes like this:

let colorsArray = fruits.map( (obj) => { 
return obj.color;
}

in es6, when you have an annonymous function with only a return statement you can omit the function square brackets, omit the arguments normal brackets (assuming you have only one argument, which u do in this case) and the return statement, which also makes it possible to write it all on the same line without losing readability, so it becomes:

let colorsArray = fruits.map( obj => obj.color );

If you're not familiar with the arrow function syntax, I advise reading more about it (here is a nice start).

Gibor
  • 1,695
  • 6
  • 20
0

fruits.map(fruit => fruit.color)

Kraken
  • 5,043
  • 3
  • 25
  • 46