ES6地图在对象数组上抛出错误

Ala*_*hen 3 javascript ecmascript-6 reactjs

const normalizeEventTypes = nextProps.events.space_events.map(obj, i => 
     obj.id
)
Run Code Online (Sandbox Code Playgroud)

我没有定义代码obj,我的对象数组看起来像这样

{
    "space_events": [{
            "id": 1,
            "name": "Anniversaries"
        },
        {
            "id": 2,
            "name": "Brand Rollout"
        }
    }]
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

May*_*kla 5

你忘记使用了(),写得像这样:

const normalizeEventTypes = nextProps.events.space_events.map((obj, i) => 
     obj.id
)
Run Code Online (Sandbox Code Playgroud)

原因:

你在map回调函数中使用obj和索引这两个参数,所以你需要()用来包装参数,如下所示:

a = b.map((i,j) => i)
Run Code Online (Sandbox Code Playgroud)

()当我们只想使用一个参数时,这些是可选的,如下所示:

a = b.map(i => i)
Run Code Online (Sandbox Code Playgroud)

不同的使用方式map:

1. a.map(i => i + 1); //when index is not required

2.

 a.map(i => {  //when want to do some calculation
       //some calculation
       return //something;
 })
Run Code Online (Sandbox Code Playgroud)

3. a.map((i,j) => i + j) //when want to use the index of item

检查工作代码段:

let data = {
    "space_events": [{
            "id": 1,
            "name": "Anniversaries"
        },
        {
            "id": 2,
            "name": "Brand Rollout"
        }
    ]
}

let result = data.space_events.map((obj,i) => obj.name);

console.log('result', result);
Run Code Online (Sandbox Code Playgroud)