意外令牌:使用地图形成对象数组 [英] unexpected token : using map to form array of object

查看:49
本文介绍了意外令牌:使用地图形成对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作这个

[
        {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)

解决方案

您缺少像({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) 

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)

这篇关于意外令牌:使用地图形成对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆