const objectExample = {hello: "🌎", goodbye: "🌙", nested: {inner: "🐦"}, array: [37]} console.log("Using Object.entries and a .forEach loop to console log key and value pairs:") Object.entries(objectExample).forEach(keyValuePair => {console.log(" ",...keyValuePair)}) // The spread operator is used as a quick way to expand the array [key, value] console.log("Alternatively, you can destructure the keys and values using a for...of loop:") for(const [key,value] of Object.entries(objectExample)) { console.log(` ${key}: ${value}`) } // Note that const is optional but recommended // A for...of example without const - defaults to var in the global scope for([key,value] of Object.entries(objectExample)) { `${key}: ${value}` } console.log("Careful! Using var means key and value are still accessible in global scope") console.log(` ${key}: ${value}`) // These vars pollute the global scope and could lead to bugs
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter