2017-02-25 227 views
1

從api響應中,我想要索引results數組而不使用forEach。我發現下面ES2016的解決方案,但是當我運行下面的JavaScript我得到EXCEPTION:response.findIndex不是函數

例外:response.findIndex不是一個函數

的JavaScript

console.log(response.findIndex(x => x.results.id === 5)); 

響應

{ 
"count": 9, 
"results": [ 
    { 
     "id": 8, 
     "name": "Example 1" 
    }, 
    { 
     "id": 9, 
     "name": "Example 2" 
    } 
    .... 
]} 

回答

2

findIndex需要數組,但您的響應是一個對象。但名爲results的屬性是一個數組。

轉換此

response.findIndex(x => x.results.id === 5) 

response.results.findIndex(x => x.id === 5) 
+2

它應該是'response.results.findIndex(X => x.id == 5)' –

+0

@NavneilNaicker感謝您指出。你有一個鷹眼隊友:) –

+0

謝謝你的作品! –