user3294288
user3294288

Reputation: 45

JSON object key value

This is my JSON response from server

{    "responses": 
              {        
                 "army":[{"name":"jhon","age":"32"},{"name":"sam".....}]      
                 "navy":[{"name":"tom","age":"42"},{"name":"josh"......}]   
                 "air":[{"name":"jhona","age":"34"},{"name":"samy"........}]   
               }  
}

I have tried:

var obj1= myArrays.responses; 
for (var key1 in obj1) { 
    console.log(key1); 
    for (var i = 0; i < obj1.length; i++) { 
        console.log(obj1.length);
    }
}

I want the output to look like this, but it I don't know how to do it.

In army, jhon(age:32), sam(age:35)
In navy, tom(age:42), josh(age:35)
In air, jhona(age:34), samy(age:35)

Upvotes: 1

Views: 135

Answers (4)

Ashley Medway
Ashley Medway

Reputation: 7301

A nice and clear answer using a series of loops. Example.

var responses = { "responses": 
                {        
                  "army":[{"name":"jhon","age":"32"},{"name":"sam","age":"42"}],      
                  "navy":[{"name":"tom","age":"42"},{"name":"josh","age":"24"}],   
                  "air":[{"name":"jhona","age":"34"},{"name":"samy","age":"32"}],   
                }
};

var output = "";
var array = responses.responses;

for(var item in array)
{
    output += "In " + item + ", ";

    for(var x = 0; x < array[item].length; x++) {
        output += array[item][x]["name"] + " (age:" + array[item][x]["age"] + ")";

        if((x + 1) === array[item].length) {
            output += "<br/>";
        } else {
            output += ", ";   
        }
    }  
}

document.getElementById("output").innerHTML = output;

OUPUT

In Army, jhon (age:32), sam (age:42)
In Navy, tom (age:42), josh (age:24)
In Air, jhona (age:34), samy (age:32)

Upvotes: 1

Bic
Bic

Reputation: 3134

Just loops:

var output = '';
for (var branch in responses) {
    ouput += 'In ' + branch + ', ';
    var people = responses[branch];
    for (var i = 0; i < people.length; i++) {
       output += people[i].name + '(age:' + people[i].age +')';
    }
}

Based on the code you added, you are missing an assigment:

var obj1= myArrays.responses; 
for (var key1 in obj1) { 
    console.log(key1); 
    var people = obj1[key1]; // get the people array
    for (var i = 0; i < people.length; i++) { 
        console.log(people[i].name, people[i].age); 
    } 
}

Upvotes: 3

dfsq
dfsq

Reputation: 193291

... or you can use for-in+map:

for (var key in data.responses) {
    console.log('In', key, data.responses[key].map(function(el) {
        return el.name + '(' + el.age + ')';
    }).join());
}

Upvotes: 1

CD..
CD..

Reputation: 74166

You can use reduce like this:

Object.keys(responses).forEach(function(key){

  console.log(responses[key].reduce(function(a ,b){
    return a + ', ' + b.name + (b.age ? '(age:' + b.age + ')' : ''); 
  }, 'In ' + key));

})

Upvotes: 1

Related Questions