簡體   English   中英

ES6地圖在對象數組上拋出錯誤

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

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
)

原因

您在map回調函數中使用obj和索引兩個參數,因此您需要使用()來包裝參數,如下所示:

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 => i + 1); //when index is not required

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

檢查工作代碼段:

 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