David Cohen David Cohen - 1 month ago 9
Javascript Question

Select particular fields from Immutable List

I have this array:

var list = [{id:1,name:'logan',color:'red'},{id:2,name:'paul', color:'green'}];


I want to get an array of objects that contains the name and color of each one.
I tried the following but im getting an array of undefined:

var array = list.map(item => {name: item.name, color: item.color});


What am I doing wrong?

Answer

When using the arrow syntax to return an object literal, you must wrap the object in () in order to differentiate it from a function body.

var list = [{
  id: 1,
  name: 'logan',
  color: 'red'
}, {
  id: 2,
  name: 'paul',
  color: 'green'
}];

var array = list.map(item => ({
  name: item.name,
  color: item.color
}));

console.log(array);

See Arrow Functions: Advanced Syntax on MDN