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)
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)
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}));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With