ES6 映射在对象数组上抛出错误


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

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

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

我错过了什么吗?

你忘了用(),这样写:

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

原因

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

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

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

a = b.map(i => i)

使用map的不同方式:

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

阿拉伯数字。

 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

检查工作片段:

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

相关内容

最新更新