There were several ways to iterate javascript object, we have choose the appropriate approach based on our platform and version of javascript.
How to iterate Javascript Object:
A simple Javascript Object iteration goes like below.
Plain old Javascript:
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB"
}
for (var key in data) {
console.log(key + " -> " + data[key]);
}
Output:
file -> 1623061746-report.xlsx
date -> 7/6/2021
size -> 41 KB
The same we can do with the below solutions.
Object.keys():
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB"
}
for (var key of Object.keys(data)) {
console.log(key + " => " + data[key])
}
Output:
file => 1623061746-report.xlsx
date => 7/6/2021
size => 41 KB
Object.keys() foreach:
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB"
}
Object.keys(data).forEach(function(key) {
console.log(key, data[key]);
});
Output:
file 1623061746-report.xlsx
date 7/6/2021
size 41 KB
Object.entries():
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB"
}
for (let [key, value] of Object.entries(data)) {
console.log( `${key} : ${value}` );
}
Output:
file : 1623061746-report.xlsx
date : 7/6/2021
size : 41 KB
Object.entries() foreach:
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB"
}
Object.entries(data).forEach(
([key, value]) => console.log(key, value)
);
Output:
file 1623061746-report.xlsx
date 7/6/2021
size 41 KB
Iterating Nested Javascript Objects:
There is no surprise or second thought, all the above examples should work without any issues for nested objects also.
var data = {
file: "1623061746-report.xlsx",
date: "7/6/2021",
size: "41 KB",
inner_data: {
file: "1623062754-report.xlsx",
date: "7/6/2021",
size: "41 KB"
},
inner_data_list: [
{
file: "1623065997-report.xlsx",
date: "7/6/2021",
size: "41 KB"
},
{
file: "1623145510-report.xlsx",
date: "8/6/2021",
size: "44 KB"
}
]
}
Object.entries(data).forEach(
([key, value]) => console.log(key, value)
);
Output:
References:
Happy Learning 🙂