unexpected token : using map to form array of obje

2020-07-16 03:34发布

问题:

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)

回答1:

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)



回答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}));


回答3:

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