Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected token : using map to form array of object [duplicate]

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)
like image 452
Alan Jenshen Avatar asked Jun 05 '17 10:06

Alan Jenshen


3 Answers

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)
like image 188
prasanth Avatar answered Nov 13 '22 11:11

prasanth


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}));
like image 40
AKX Avatar answered Nov 13 '22 13:11

AKX


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);
like image 1
Arg0n Avatar answered Nov 13 '22 11:11

Arg0n