【问题标题】:Get values in an array of JSON objects获取 JSON 对象数组中的值
【发布时间】:2010-12-31 14:14:00
【问题描述】:

我有一个 JSON 对象数组,如下所示:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

我想遍历它们并在列表中回显它们。我该怎么做?

【问题讨论】:

  • 只是补充一下,json 没有什么特别之处。它只是一个 javascript 对象初始化图。在您的示例中,您有一个数组(方括号),其中包含对象(大括号语法)。您应该检查 javascript 中的对象和数组文字以揭示“魔术”

标签: javascript arrays json loops


【解决方案1】:

你的意思是这样的?

 var a = [
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" }
 ];

 function iter() {
     for(var i = 0; i < a.length; ++i) {
         var json = a[i];
         for(var prop in json) {
              alert(json[prop]);
                          // or myArray.push(json[prop]) or whatever you want
         }
     }
 }

【讨论】:

    【解决方案2】:
    var json = [
        { name: "tom", text: "tasty" },
        { name: "tom", text: "tasty" },
        { name: "tom", text: "tasty" },
        { name: "tom", text: "tasty" },
        { name: "tom", text: "tasty" }
    ]
    
    for(var i in json){
        var json2 = json[i];
        for(var j in json2){
            console.log(i+'-'+j+" : "+json2[j]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      另一种解决方案:

      var jsonArray = [
        { name: "Alice", text: "a" },
        { name: "Bob",   text: "b" },
        { name: "Carol", text: "c" },
        { name: "Dave",  text: "d" }
      ];
      
      jsonArray.forEach(function(json){
        for(var key in json){
          var log = "Key: {0} - Value: {1}";
          log = log.replace("{0}", key); // key
          log = log.replace("{1}", json[key]); // value
          console.log(log);
        }
      });
      

      如果您想针对较新的浏览器,可以使用Objects.keys

      var jsonArray = [
        { name: "Alice", text: "a" },
        { name: "Bob",   text: "b" },
        { name: "Carol", text: "c" },
        { name: "Dave",  text: "d" }
      ];
      
      jsonArray.forEach(function(json){
        Object.keys(json).forEach(function(key){
          var log = "Key: {0} - Value: {1}";
          log = log.replace("{0}", key); // key
          log = log.replace("{1}", json[key]); // value
          console.log(log);
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 2020-05-10
        • 1970-01-01
        相关资源
        最近更新 更多