2017-02-25 231 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

谢谢你的作品! –