Search code examples
javascriptjsonapiparsingecmascript-5

JSON Parse to get objects within array


I've never done anything like this before and are struggling to get this working, I have tried different code samples online but to no joy.

I want to return the displayName from the 5 objects in the below array.

array example

first

I'm restricted to only use ES5.

I tried the below but was only getting the first object when printing rather than all 5.

for (var i = 0; i < parsed.value.length; i++) {
    var counter = parsed.value[i].displayName;
}

Any tips/points? As you can tell I'm new to this!

Thanks.


Solution

  • You can also have a look at the below simple examples.

    These examples do not include all the fields from your input data but relevant.

    I think, it will be helpful.

    var parsed = {
        value:  [
            {fullName:  "Ken Thompson",  displayName:  "Ken",  age:  55}, 
            {fullName:  "Rob Pike",  displayName:  "Rob",  age:  50}, 
            {fullName:  "Robert Griesemer",  displayName:  "RobertGoog",  age:  56}, 
            {fullName:  "Ander Hezlsberg",  displayName:  "AndersMicro",  age:  58}, 
            {fullName:  "Ryan Dahl",  displayName:  "Ryan08",  age:  40}
         ]
    };
    
    // 1st way to get as an array of objects
    var dispNames = parsed.value.map(function(o) { return {displayName: o.displayName}});
    console.log(dispNames);
    
    /*
    [ { displayName: 'Ken' },
      { displayName: 'Rob' },
      { displayName: 'RobertGoog' },
      { displayName: 'AndersMicro' },
      { displayName: 'Ryan08' } ]
    */
    
    // 2nd way to get as a list of displayNames
    var dispNames2 = parsed.value.map(function(o) { return o.displayName});
    console.log(dispNames2);
    /*
        [ 'Ken', 'Rob', 'RobertGoog', 'AndersMicro', 'Ryan08' ]
    */
    
    // 3rd way to get as a string with displayNames separated with comma(,) 
    console. log(dispNames2.join(","));
    /*
        Ken,Rob,RobertGoog,AndersMicro,Ryan08
    */
    

    If you want to get result as the above 3rd way shows, here is most simple way to get that without using join() method defined on array objects.

    console.log("" + dispNames2);
    // Ken,Rob,RobertGoog,AndersMicro,Ryan08