How to get the first key pair in array of JSON?

  • A+
Category:Languages

Currently, I have my JSON and a function that loops through the results and then through the URLs. I am trying to only get the first type value which is detail. I have tried looking for ways to get the first value and found that using [0] can work in some situations but not this one. Am I indexing incorrectly? and is there a more succinct way of coding this nested for loop?

const data = {   "data": {     "results": [{       "name": "Deadpool",       "urls": [{           "type": "detail",           "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         },         {           "type": "wiki",           "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         },         {           "type": "comiclink",           "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         }       ]     }]   } };  function test(data) {   const dataArr = data.data['results'];   for (let i = 0; i < dataArr.length; i++) {     console.log(dataArr[i].urls);     const urlArr = dataArr[i].urls     for (let j = 0; j < urlArr.length; j++) {       console.log(urlArr[j].type[0]);     }   } }  test(data);

 


You can use find to find the exact element by type prop.

const data = {   "data": {     "results": [{       "name": "Deadpool",       "urls": [{           "type": "detail",           "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         },         {           "type": "wiki",           "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         },         {           "type": "comiclink",           "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"         }       ]     }]   } };  function test(data) {   const dataArr = data.data['results'];   for (let i = 0; i < dataArr.length; i++) {     //console.log(dataArr[i].urls);     const urlArr = dataArr[i].urls     const detail = urlArr.find(url => url.type == 'detail');     console.log(detail.url);   } }  test(data);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: