简体   繁体   English

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

[英]ES6 map is throwing error on array of object

const normalizeEventTypes = nextProps.events.space_events.map(obj, i => 
     obj.id
)

I code obj is not defined, my array of object look like this 我没有定义代码obj,我的对象数组看起来像这样

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

am I missing something? 我错过了什么吗?

You forgot to use () , write it like this: 你忘了使用() ,像这样写:

const normalizeEventTypes = nextProps.events.space_events.map((obj, i) => 
     obj.id
)

Reason : 原因

You are using obj and index both parameters in map callback function so you need to use () to wrap the parameters, like this: 您在map回调函数中使用obj和索引两个参数,因此您需要使用()来包装参数,如下所示:

a = b.map((i,j) => i)

These () are optional when we want to use only one parameter, like this: 当我们只想使用一个参数时,这些()是可选的,如下所示:

a = b.map(i => i)

Different ways of using map : 使用map不同方式:

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

2. 2。

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

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

Check the working snippet: 检查工作代码段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM