0
$.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)
    }    
});

event is only catch last event data. for loop does not seem to be doing the job. I need to get a JSON and create a new JSON in a format other than it.

soure json: http://aratarikan.com/api/posts?format=json target json format: http://aratarikan.com/static/data.json

Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • Your problem is because you're creating a new `events` array on each iteration - you want to declare `events` outside (just before) the for loop. – Tom O. Jul 09 '18 at 22:00

2 Answers2

2

Define events before for loop:

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)
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

In your code, you are reinitialising the event array inside the for-loop. That is causing the problem. You need to initialise it outside the for-loop. Also you need to re-initialise the event object at the start of each loop.

Following code should work:

$.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);   
});
Dhruv Shah
  • 1,611
  • 1
  • 8
  • 22