Dhana Dhana - 7 months ago 14
Javascript Question

How to iterate json object structure to get only names?

I have the following json object, how can I get/loop only to get the names values ?

var jsonobject = {
"jsontest": [{
"name": "firstnamevalue",
"firstkey": "firstvalue"

}, {
"name": "secondnamevalue",
"secondkey": "secondvalue",
"thirdkey": false
}, {
"name": "thirdnamevalue",
"fourthkey": null
}],
"fifthkey": "testvalues"
}


I need only name values, like:
firstnamevalue, secondnamevalue, thirdnamevalue
on my alert message ? Please let me know and thanks in advance.

Answer

you can use javascript map method to get the array values based on your requirement.

  var results = jsonobject.jsontest.map(function(item,index){
     return item["name"];

    })
    results //
["firstnamevalue", "secondnamevalue", "thirdnamevalue"]

ES2015 with fat arrow (ES6)

jsonobject.jsontest.map((item,index)=> item["name"])