handsome
handsome

Reputation: 2422

Return only some keys from an array of objects

I want to display the array but only with name and age

 const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
let userList =  users.map(users => {name: users.name, users.instrument })
console.log(userList);

didn't work. I'm missing a return somewhere right?

Upvotes: 2

Views: 3298

Answers (3)

Mamun
Mamun

Reputation: 68933

You should wrap the object statement in each iteration with ().

Also, I prefer using Destructuring assignment:

const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var new_users = users.map(({name,instrument})  => ({name, instrument}));
console.log(new_users);

Upvotes: 5

lyne
lyne

Reputation: 72

  1. You forgot an = when setting users.
  2. Inside the map function, you called the run-through-object users but use user.
  3. You forgot an ' after 'guitar
  4. You didn't set the key for the instrument value in the mapping function
  5. You need to add brackets () around the object in the mapping function as it will be treated as arrow function if forgotten

In the end it should look like this:

const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];

const mapped = users.map(user => ({name: user.name, instrument: user.instrument}));

console.log(mapped);

Upvotes: 1

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

You just need to wrap object inside ()

const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var result = users.map(user => ({ name: user.name, instrument: user.instrument }));
console.log(result)

Upvotes: 3

Related Questions