2

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1
  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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.