How to Iterate Over a JavaScript Object

How to iterate over a JavaScript object?

For iterating on keys of Arrays, Strings, or Objects, use for .. in :

for (let key in yourobject) {
console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (let i=300; i < keys.length && i < 600; i++) { 
console.log(keys[i], yourobject[keys[i]]);
}

How do I loop through or enumerate a JavaScript object?

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {

"p1": "value1",

"p2": "value2",

"p3": "value3"

};

for (var key in p) {

if (p.hasOwnProperty(key)) {

console.log(key + " -> " + p[key]);

}

}

Iterate an object on a specific order

You could,

  1. Get the properties of the object as an array using Object.keys().
  2. Sort the properties of the object using sort().
  3. Use forEach() to iterate through the sorted items (which is executed in ascending order of the array).

var items = {

"a": {

"text": "text",

"index": 5

},

"b": {

"text": "text",

"index": 3

},

"c": {

"text": "text",

"index": 1,

}

};

Object.keys(items).sort(function(a, b) {

return items[a].index - items[b].index;

}).forEach(doStuff);

function doStuff(key) {

console.log(items[key]);

}

How can I loop through a JavaScript object array?

It appears you may just have missed the "messages" property in the data, so the loop is likely iterating the root Object rather than the Array:

for (var key in data.messages) {
var obj = data.messages[key];
// ...
}

Unless data was set to messages before the given snippet.

Though, you should consider changing that to a normal for loop for the Array:

for (var i = 0, l = data.messages.length; i < l; i++) {
var obj = data.messages[i];
// ...
}

How to loop through a plain JavaScript object with the objects as members

for (var key in validation_messages) {
// skip loop if the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;

var obj = validation_messages[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(prop)) continue;

// your code
alert(prop + " = " + obj[prop]);
}
}

Looping through an object and changing all values

try

var superSecret = function(spy){
Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
return spy;
}

How to iterate over this javascript object?

Use for in syntax for iteration object properties.

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};

for(const item in objResult)

console.log(objResult[item])

How to iterate through an object containing arrays?

You can use Object.entries to loop over all the key-value pairs of the object and use Array#forEach to loop over the values.

var data = {
Peoples : [{thisMonthImpr:1450, thisConversionValue:0.0, name:"Peoples", thisMonthClicks:17}],
Noor : [{thisMonthImpr:154706, thisConversionValue:0.0, name:"Noor", thisMonthClicks:176}, {thisMonthImpr:234286, thisConversionValue:0.0, name:"Noor", thisMonthClicks:1217}],
HIHFAD : [{thisMonthImpr:126, thisConversionValue:0.0, name:"HIHFAD", thisMonthClicks:0}, {thisMonthImpr:39795, thisConversionValue:0.0, name:"HIHFAD", thisMonthClicks:104}],
AlAnsari : [{thisMonthImpr:57724, thisConversionValue:0.0, name:"AlAnsari", thisMonthClicks:57}, {thisMonthImpr:100374, thisConversionValue:0.0, name:"AlAnsari", thisMonthClicks:538}, {thisMonthImpr:12183, thisConversionValue:0.0, name:"AlAnsari", thisMonthClicks:99}],
Aryana : [{thisMonthImpr:116294, thisConversionValue:0.0, name:"Aryana", thisMonthClicks:467}, {thisMonthImpr:20940, thisConversionValue:0.0, name:"Aryana", thisMonthClicks:24}],
Hhugs : [{thisMonthImpr:88, thisConversionValue:0.0, name:"Hhugs", thisMonthClicks:0}, {thisMonthImpr:0, thisConversionValue:0.0, name:"Hhugs", thisMonthClicks:0}],
Hihfad : [{thisMonthImpr:24378, thisConversionValue:0.0, name:"Hihfad", thisMonthClicks:222}, {thisMonthImpr:20841, thisConversionValue:0.0, name:"Hihfad", thisMonthClicks:197}],
GLM : [{thisMonthImpr:175, thisConversionValue:0.0, name:"GLM", thisMonthClicks:0}, {thisMonthImpr:51909, thisConversionValue:0.0, name:"GLM", thisMonthClicks:465}],
Ummah : [{thisMonthImpr:45219, thisConversionValue:5.0, name:"Ummah", thisMonthClicks:13635}, {thisMonthImpr:141961, thisConversionValue:0.0, name:"Ummah", thisMonthClicks:933}, {thisMonthImpr:17745, thisConversionValue:0.0, name:"Ummah", thisMonthClicks:165}]
};
const container = document.querySelector("#container");
const tableHead = `<tr><th>This Month Impr</th><th>This Month Clicks</th><th>This Month Conv Value</th></tr>`;
Object.entries(data).forEach(([label,values])=>{
const title = document.createElement('h1');
const table = document.createElement('table');
title.textContent = label;
table.innerHTML = tableHead;
values.forEach(({thisMonthImpr,thisConversionValue,thisMonthClicks})=>{
const row = document.createElement('tr');
const tds = Array.from({length:3},()=>document.createElement('td'));
tds[0].textContent = thisMonthImpr;
tds[1].textContent = thisConversionValue;
tds[2].textContent = thisMonthClicks;
tds.forEach(td=>row.appendChild(td));
table.appendChild(row);
});
container.appendChild(title);
container.appendChild(table);
});
table {
border-collapse: collapse;
}

table, th, td {
border: 1px solid black;
}

td {
padding: 10px;
}
<div id="container"></div>


Related Topics



Leave a reply



Submit