How to iterate object in JavaScript? [duplicate]

You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.

var data = dictionary.data;

for (var i in data)
{
     var id = data[i].id;
     var name = data[i].name;
}

You can follow similar approach to iterate the image array.


There's this way too (new to EcmaScript5):

dictionary.data.forEach(function(item){
    console.log(item.name + ' ' + item.id);
});

Same approach for images


Something like that:

var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};

for (item in dictionary) {
  for (subItem in dictionary[item]) {
     console.log(dictionary[item][subItem].id);
     console.log(dictionary[item][subItem].name);
  }
}

Use dot notation and/or bracket notation to access object properties and for loops to iterate arrays:

var d, i;

for (i = 0; i < dictionary.data.length; i++) {
  d = dictionary.data[i];
  alert(d.id + ' ' + d.name);
}

You can also iterate arrays using for..in loops; however, properties added to Array.prototype may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.


Using a generator function you could iterate over deep key-values.

function * deepEntries(obj) { 
    for(let [key, value] of Object.entries(obj)) {
        if (typeof value !== 'object') 
            yield [key, value]
        else 
            for(let entries of deepEntries(value))
                yield [key, ...entries]
    }
}

const dictionary = {
    "data": [
        {"id":"0","name":"ABC"},
        {"id":"1","name":"DEF"}
    ],
    "images": [
        {"id":"0","name":"PQR"},
        {"id":"1","name":"xyz"}
    ]
}

for(let entries of deepEntries(dictionary)) {
    const key = entries.slice(0, -1).join('.')
    const value = entries[entries.length-1]
    console.log(key, value)
}