我想制作这个
[
{name: "james", age: 10},
{name: "john", age: 12},
{name: "johnny", age: 56}
]
我的下面的代码失败了,得到了预期的令牌?
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 :(得分:7)
您错过了此()
({name:obj.name, age:obj.age})
更改
您必须将返回的对象文字包装到括号中。除此以外 花括号将被视为表示函数的主体。下一个 工作原理:
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 :(得分:1)
使用箭头表达式创建对象时,您需要将主体包裹在parens中,或者将其解析为箭头函数:
let y = x.map(obj => ({name: obj.name, age: obj.age}));
答案 2 :(得分:1)
作为参考,这也可以,并且是相同的:
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);