mangokitty
mangokitty

Reputation: 2329

loop through list of dictionaries in Javascript

I'm trying to loop through a list of dicitionaries returned from my python Flask api and insert the information into a row in a table where the first column is the Event "type" and the second column is "Event Time". The list of dicitonaries looks like this:

        { "type": "Creation Event", "time": event_results[0] },
        { "type": "Deletion Event", "time": event_results[1] },
        { "type": "Last Update Event", "time": event_results[2] }

Here is my current way of filling in the table

       return this.getData().then(event => {
           this.clear()

           this.addRow(['Event Type', 'Event Time'], 'th')

           if (!event) return;

           Object.keys(event).forEach(dict in list => {
               this.addRow([this.dict[type], dict[time]])
           })
       })
   }

Any advice on this is greatly appreciated.

Upvotes: 1

Views: 6154

Answers (1)

Taki
Taki

Reputation: 17654

You can loop through the array of objects directly using forEach:

event.forEach(dict => this.addRow([obj.type, obj.time]));

your code :

return this.getData().then(event => {
  this.clear();

  this.addRow(["Event Type", "Event Time"], "th");

  if (!event) return;

  event.forEach(({type, time}) => this.addRow([type, time]));
});

Upvotes: 5

Related Questions