1

I'm studying the map function and tried to make a contrived example which I thought would work. This code works fine:

let students = [{name: 'Susan', grades: [88, 38, 28]}, {name: 'Robert', grades: [28,97, 17]}];
let newStudents = students.map((el) => el.name);  
console.log(newStudents); // [ 'Susan', 'Robert' ]

But what I really wanted was the following in the map function:

let newStudents = students.map((el) => {name: el.name});
// [ undefined, undefined ]
// I assumed to get back the following: [ {name: 'Susan'}, {name: 'Robert'} ]

Why is using an object in the return portion of the map function not allowed?

1
  • 1
    Try this let newStudents = students.map((el) => {return {name: el.name}}); Commented Jul 27, 2017 at 6:06

1 Answer 1

4

You need to wrap the object in normal function parenthesis.

let newStudents = students.map((el) => ({name: el.name}));
                                        ^              ^

let students = [{name: 'Susan', grades: [88, 38, 28]}, {name: 'Robert', grades: [28,97, 17]}];
let newStudents = students.map((el) => ({name: el.name}));
console.log(newStudents);

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

2 Comments

Ah ok thank you. And why exactly do I need the extra parenthesis?
It causes an explicit return. Without them or return the curly brakets denote a function block.

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.