David Cohen David Cohen - 1 year ago 82
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 Source

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


See Arrow Functions: Advanced Syntax on MDN

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download