Looping over an Array vs. looping over an Object
August 22, 2021
- Data needs to be modelled differently
- It's easier to find things in an object with key value pairs than it is in an array
- You'll see the object of objects sort of data modeling in usage of state libraries like Redux where we have data stores and need to get values from those stores after finding them first..
Array containing (anonymous) objects
code
[
{
name: "Iceland",
dialCode: "+354",
alpha2code: "IS",
alpha3code: "ISL",
flag: "ISL.svg",
},
{
name: "Brazil",
dialCode: "+55",
alpha2code: "BR",
alpha3code: "BRA",
flag: "BRA.svg",
},
// {...}
];
Looping over it with .map()
code
countriesDataObject
.map((country) => {
return `<li>
<img src="data/flags/${country.flag}" className="flag" alt="${country.name}" title="${country.name}" />
${country.dialCode}
</li>`;
})
.join("");
Object containing (named) objects
code
{
"ISL" : {
name: 'Iceland',
dialCode: '+354',
alpha2code: 'IS',
alpha3code: 'ISL',
flag: 'ISL.svg',
},
BRA: {
name: "Brazil",
dialCode: "+55",
alpha2code: "BR",
alpha3code: "BRA",
flag: "BRA.svg",
},
// {...}
}
Looping over it with a for ... in loop and Object.entries()
code
let html = "";
for (const [key, value] of Object.entries(countriesDataObject)) {
html += `<li><img src="data/flags/${value.flag}" className="flag" alt="${value.name}" title="${value.name}" /> ${value.dialCode}</li>`;
}
return html;