Notes

Looping over an Array vs. looping over an Object

Edit on GitHub

JavaScript
2 minutes
  • 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

 1;[
 2  {
 3    name: 'Iceland',
 4    dialCode: '+354',
 5    alpha2code: 'IS',
 6    alpha3code: 'ISL',
 7    flag: 'ISL.svg',
 8  },
 9  {
10    name: 'Brazil',
11    dialCode: '+55',
12    alpha2code: 'BR',
13    alpha3code: 'BRA',
14    flag: 'BRA.svg',
15  },
16  // {...}
17]

Looping over it with .map()

1countriesDataObject
2  .map((country) => {
3    return `<li>
4            <img src="data/flags/${country.flag}" class="flag" alt="${country.name}" title="${country.name}" />
5            ${country.dialCode}
6          </li>`
7  })
8  .join('')

Object containing (named) objects

 1{
 2  "ISL" : {
 3    name: 'Iceland',
 4    dialCode: '+354',
 5    alpha2code: 'IS',
 6    alpha3code: 'ISL',
 7    flag: 'ISL.svg',
 8  },
 9  BRA: {
10    name: "Brazil",
11    dialCode: "+55",
12    alpha2code: "BR",
13    alpha3code: "BRA",
14    flag: "BRA.svg",
15  },
16  // {...}
17}

Looping over it with a for ... in loop and Object.entries()

1let html = ''
2
3for (const [key, value] of Object.entries(countriesDataObject)) {
4  html += `<li><img src="data/flags/${value.flag}" class="flag" alt="${value.name}" title="${value.name}" />  ${value.dialCode}</li>`
5}
6
7return html