6

I want to produce this

[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]

My below code failed, got expected token?

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)
Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

3 Answers3

14

you are missing the () change like this ({name:obj.name, age:obj.age})

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. Next works:

Reference question

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => ({name:obj.name, age:obj.age}))

console.log(y)
prasanth
  • 22,145
  • 4
  • 29
  • 53
2

When creating objects with arrow expressions, you'll need to wrap the body in parens, or it'll be parsed as an arrow function:

let y = x.map(obj => ({name: obj.name, age: obj.age}));
AKX
  • 152,115
  • 15
  • 115
  • 172
1

Just as a reference, this would also work, and be the same:

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
];

let y = x.map(obj => {
  return { name:obj.name, age:obj.age };
});

console.log(y);
Arg0n
  • 8,283
  • 2
  • 21
  • 38