JSON对象键值

时间:2014-02-10 19:08:34

标签: javascript json

这是我来自服务器的JSON响应

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

我试过了:

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

我希望输出看起来像这样,但我不知道该怎么做。

  

在军队中,jhon(年龄:32岁),山姆(年龄:35岁)   在海军,汤姆(年龄:42),乔什(年龄:35)
  在空中,jhona(年龄:34岁),samy(年龄:35岁)

4 个答案:

答案 0 :(得分:3)

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 +')';
    }
}

根据您添加的代码,您错过了一个分配:

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); 
    } 
}

答案 1 :(得分:1)

您可以像这样使用reduce

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));

})

答案 2 :(得分:1)

...或者您可以使用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());
}

答案 3 :(得分:1)

使用一系列循环的清晰答案。 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

  

陆军,jhon(年龄:32岁),山姆(年龄:42岁)   在海军中,汤姆(年龄:42岁),乔什(年龄:24岁)   在Air,jhona(年龄:34岁),samy(年龄:32岁)