Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中迭代json数组_Javascript_Json_Iteration - Fatal编程技术网

如何在javascript中迭代json数组

如何在javascript中迭代json数组,javascript,json,iteration,Javascript,Json,Iteration,是的,有很多关于这个的帖子。但我的怀疑是没有什么不同。我有以下数组为例 var dictionary = { "12Jan2013": [{ "id": "0", "name": "ABC" }, { "id": "1", "name": "DEF" }], "13Jan2013": [{ "id": "0", "name": "PQR" }, {

是的,有很多关于这个的帖子。但我的怀疑是没有什么不同。我有以下数组为例

var dictionary = {
    "12Jan2013": [{
        "id": "0",
        "name": "ABC"
    }, {
        "id": "1",
        "name": "DEF"
    }],
    "13Jan2013": [{
        "id": "0",
        "name": "PQR"
    }, {
        "id": "1",
        "name": "xyz"
    }]
};
同一个站点上有相同的帖子,但在字典
json
中,数组键是动态的
。这里是日期ie 2013年1月12日。它可以是任何日期。它不是静态的。我已经搜索过了,但没有得到解决方案

如何迭代这种json数组?

以及如何以上述相同格式打印json数组?

编辑

这是我的真实代码。我在下面的代码中显示了一条注释,我想在
回调中迭代
数据,即
jsonData
var

var arrAllrecords = [];
var arrCityrecordForADay = [];
function getWeatherDataForCities(cityArray, callback){

var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){

    for(var j=1; j<=1; j++){
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){                    
                var arrCityRecordForDay = [];
                /*arrCityrecordForADay.push(data.list[0].city.name);
                arrCityrecordForADay.push(data.list[0].weather[0].description);
                arrCityrecordForADay.push(timeConverter(data.list[0].dt));
                arrCityrecordForADay.push(data.list[0].main.temp);
                arrCityrecordForADay.push(data.list[0].main.humidity);
                arrCityrecordForADay.push(data.list[0].main.pressure)
                arrCityrecordForADay.push(data.list[0].wind.speed);*/
                //'{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';

                arrCityRecordForDay.push(
                    {"cityName" : data.list[0].city.name},
                    {"weather" : data.list[0].weather[0].description}
                );

                var tempId = data.list[0].city.name+"-"+timeConverter(data.list[0].dt);

                arrCityrecordForADay.push(
                    {tempId : arrCityRecordForDay}
                );

                if(((arrCityrecordForADay.length)) === cityArray.length) {
                    callback(arrCityrecordForADay);
                }

        } });
        toDaysTimestamp = toDaysTimestamp - (24*60*60);
    }   
}       
}

$(document ).ready(function() {

 var cityArray = new Array();
  cityArray[0] = "pune";

  getWeatherDataForCities(cityArray, function(jsonData) {
        // Here I want to iterate jsonData
  });


});
var arrAllrecords=[];
var arrCityrecordForADay=[];
函数getWeatherDataForCities(cityArray,回调){
var toDaysTimestamp=Math.round((new Date()).getTime()/1000)-(24*60*60);
用于(cityArray中的变量i){

for(var j=1;j可以使用for循环

for (var i in json) {
 ...
}
然后,
i
是当前键,因此,您可以访问json[i]并将数据获取到相应的索引


然后,如果需要迭代内部元素,也可以执行相同的操作。

用于in…类似于:

for (var i in dictionary) {
    dictionary[i].forEach(function(elem, index) {
        console.log(elem, index);
    });
}
function strung(arg) {
    var ret = '';
    if (arg instanceof Array) {
        arg.forEach(function(elem, index) {
            ret += strung(elem) + ',';
        });
    } else if (arg instanceof Object) {
        Object.keys(arg).forEach(function(key) {
            ret += key + ': /' + strung(arg[key]) + '/';
        });
    } else if (typeof arg === "string" || typeof arg === "number") {
        ret = arg;
    }
    return ret;
}

document.body.innerHTML = strung(jsonData);
其中,
i
将遍历您的
dictionary
对象,然后您可以对dictionary中的每个json数组使用
forEach
(使用
dictionary[i]

使用此代码,您将获得

Object {id: "0", name: "ABC"} 0 
Object {id: "1", name: "DEF"} 1 
Object {id: "0", name: "PQR"} 0 
Object {id: "1", name: "xyz"} 1 
您可以定制forEach函数定义(替换
console.log
bit)来处理它

编辑:使用
Object.keys执行相同的操作

Object.keys(dictionary).forEach(function(key) {
    dictionary[key].forEach(function(elem, index) {
        console.log(elem, index);
    });
});
Edit2:考虑到
jsonData
对象的结构有点复杂,您可以尝试使用(某种)通用函数,分别作用于每种类型的组件。我可能错过了一些例子,但可能类似于:

for (var i in dictionary) {
    dictionary[i].forEach(function(elem, index) {
        console.log(elem, index);
    });
}
function strung(arg) {
    var ret = '';
    if (arg instanceof Array) {
        arg.forEach(function(elem, index) {
            ret += strung(elem) + ',';
        });
    } else if (arg instanceof Object) {
        Object.keys(arg).forEach(function(key) {
            ret += key + ': /' + strung(arg[key]) + '/';
        });
    } else if (typeof arg === "string" || typeof arg === "number") {
        ret = arg;
    }
    return ret;
}

document.body.innerHTML = strung(jsonData);

请注意,您的只是一个JavaScript数组对象。为了便于理解,您可以像下面这样对其进行迭代:

for (var i in dictionary) {
    // do something with i
    // here i will contain the dates

    for (n = 0; n < dictionary[i].length; n++) {
        // do something with the inner array of your objects    
        // dictionary[i][n].id contains the "id" of nth object in the object i
        // dictionary[i][n].name contains the "name" of nth object in the object i
    }
}
12Jan2013 : (id = 0, name = ABC) (id = 1, name = DEF)  
13Jan2013 : (id = 0, name = PQR) (id = 1, name = XYZ)

您可以在
中为…使用
,但应将其与
hasOwnProperty
结合使用,否则您将发现自己迭代继承的属性可能会破坏代码

  for (var key in object) {
    if (object.hasOwnProperty(key)) {
        // Do stuff.
    }
  }

这不是一个JSON数组,这是一个JS数组对象。它们不一样。JSON是一种数据序列化格式。我不是重复的。这里有像数据一样的常量键,这里有动态键。我不清楚这是JSON还是像Benjamin上面说的那样只是数组如果你使用
forEach
你也可以使用
object.keys
and一直都有漂亮的代码:)还要注意,您还需要使用
hasOwnProperty(i)
以过滤掉可能继承的属性。@BenjaminGruenbaum我对
对象不太满意。键
我对我的答案添加了一个编辑。这是你的意思吗?@PrashantShilimkar我已经在我的答案中添加了小提琴链接。请注意look@PrashantShilimkar乍一看,我觉得你的代码没问题(我假设
timeConverter
在别处定义)。让我补充一点,你不能直接用我的答案来回答你的
jsonData
对象,因为它的结构稍有不同。请看这个,谢谢。我编辑了我的问题,在哪里创建了动态json数组。这是正确的方法还是我所做的是正确的?@PrashantShilimkar:这一切都取决于
数据的结构尽管如此,这个概念仍然是一样的。