Created
December 14, 2020 23:06
-
-
Save DoctorDerek/c4528ead671aabd8129f6c6ee8947a9d to your computer and use it in GitHub Desktop.
Are JavaScript Object Keys Ordered and Iterable?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Typical object declared with object literal notation | |
| const myObject = { zap: "β‘" } | |
| myObject.boom = "π£" | |
| // ES5 version using for...in loop | |
| for (const key in myObject) { | |
| if (myObject.hasOwnProperty(key)) { | |
| console.log(`myObject["${key}"] is ${myObject[key]}`) | |
| } | |
| } | |
| // Output: | |
| // myObject["zap"] is β‘ | |
| // myObject["boom"] is π£ | |
| // ES6 version using Object.entries() | |
| for (const [key, value] of Object.entries(myObject)) { | |
| console.log(`myObject["${key}"] is ${value}`) | |
| } | |
| // Output: | |
| // myObject["zap"] is β‘ | |
| // myObject["boom"] is π£ | |
| // Compare to using an ES6 Map object: | |
| const myOrderedMap = new Map() | |
| myOrderedMap.set("zap", "β‘") | |
| myOrderedMap.set("boom", "π£") | |
| for (const [key, value] of myOrderedMap) { | |
| console.log(`myOrderedMap.get("${key}") is ${value}`) | |
| } | |
| // Output: | |
| // myOrderedMap.get("zap") is β‘ | |
| // myOrderedMap.get("boom") is π£ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment