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

3 Answers 3

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)

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

2 Comments

would new Object({name:obj.name, age:obj.age}) work too?
@AyoubLaazazi .. Ya of course. But ({}) is enough .short form declaration.
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}));

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.