Sometimes your data structure might be a complex object that contains a bunch of key/value pairs. Iterating over each pair is a little odd at first glance depending on what languages you’re used to but its straightforward once you get used to using the functions of Object
.
After you grab the objects keys you can loop through the keys and values at the same time. In this example you have access to each pair using the key
and value
variables during the loop.
let myObject = { one: 1, two: 2, three: 3 };
Object.keys(myObject).forEach((key, value) => {
//...do something
console.log(key, value);
});
Source
https://levelup.gitconnected.com/6-javascript-code-snippets-for-solving-common-problems-33deb6cacef3