JavaScript push()覆盖现有数据

时间:2018-07-06 09:38:33

标签: javascript jquery json

$.getJSON("http://aratarikan.com/api/posts?format=json").done(function (json) {
    resultsTop = json.results;
    sumTop = resultsTop.length;
    for (i=0; i<sumTop; i++){
        resultTop = resultsTop[i];
        var event = [];
        event ["id"] = resultTop.id;
        event ["pu"] = resultTop.publish_date;
        event ["ti"] = resultTop.title;

        var events =[];
        events.push(event);
        console.log(events)
    }    
});

事件仅捕获最后一个事件数据。 for循环似乎并没有完成任务。我需要获取JSON并以其他格式创建新的JSON。

源json:http://aratarikan.com/api/posts?format=json 目标json格式:http://aratarikan.com/static/data.json

2 个答案:

答案 0 :(得分:2)

定义events 之前 for循环:

var events =[];
for (i=0; i<sumTop; i++){
    resultTop = resultsTop[i];
    var event = [];
    event ["id"] = resultTop.id;
    event ["pu"] = resultTop.publish_date;
    event ["ti"] = resultTop.title;

    events.push(event);
}    
console.log(events)

答案 1 :(得分:0)

在您的代码中,您正在for循环内重新初始化事件数组。那就是问题所在。您需要在for循环之外对其进行初始化。 另外,您还需要在每个循环开始时重新初始化事件对象。

以下代码应该可以工作:

$.getJSON("http://aratarikan.com/api/posts?format=json").done(function (json) {
    resultsTop = json.results;
    sumTop = resultsTop.length;
    var events = [];
    for (i=0; i<sumTop; i++){

        resultTop = resultsTop[i];
        var event = {};        
        event ["id"] = resultTop.id;
        event ["pu"] = resultTop.publish_date;
        event ["ti"] = resultTop.title;
        events.push(event);
    }   
    console.log(events);   
});