Explain Codes LogoExplain Codes Logo

How to loop through a plain JavaScript object with the objects as members

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton ShumikhinยทSep 25, 2024
โšกTLDR

Here's a solid, get-the-job-done method. Use Object.entries() โ€“ it gives you key: value pairs like a generous server at a top restaurant:

const myObject = { a: 1, b: 2, c: 3 }; Object.entries(myObject).forEach(([key, value]) => { console.log(`Key: ${key}, Value: ${value}`); });

Straight out of ES6, this function is just as elegant as your grandma's pearls and holds the golden rule of iteration - keep it simple, developer! ๐Ÿ’ก

Digging deeper: methods and considerations

Using for...in and playing it safe

We know for...in , right? Grandad JavaScript's way of giving access to enumerable properties:

const myObj = { name: "Alex", location: "Nowhere" }; for (let key in myObj) { if (myObj.hasOwnProperty(key)) { console.log(key + ": " + myObj[key]); // "Alex: Nowhere" Ouch, no need to be so blunt, Alex! } }

Remember the downtown code block: always have your hasOwnProperty on you to avoid running into any unwanted prototype chain shenanigans.

Unpacking nested objects with recursion

When objects get nested like a set of Russian dolls, here's how we crack em':

function traverseObject(obj) { Object.entries(obj).forEach(([key, value]) => { if (typeof value === "object") { return traverseObject(value); // Recursive call, we're going inception mode } console.log(`Key: ${key}, Value: ${value}`); }); }

Thanks to recursion, we've got a trusty Swiss army knife for deep property extraction. Now that's deep.

Functional programming for a state-of-mind change

Functional programming is like going vegan - a bit challenging but undeniably transformative:

const transformed = Object.fromEntries( Object.entries(myObj).map(([key, value]) => [key, value.toString().toUpperCase()]) ); // Function manipulationValue has gone on vacation, feel free to Map()

Data is immutable and our changes are tangible - just the way we like it.

Debug like a Sherlock

Console debugging the CIA way

Spies love secrets. Programmers? Not so much. Hence our need for powerful debugging tools:

Object.entries(obj).forEach(([key, value]) => { console.debug(`Inspecting ${key}:`, value); // "This is Control. Report, Agent" vibes });

Preserving object purity in a messy world

Double-check hasOwnProperty because when you think no one is watching, the prototype chain sneaks in:

for (let key in outerObj) { if (outerObj.hasOwnProperty(key)) { const innerObj = outerObj[key]; for (let nestedKey in innerObj) { if (innerObj.hasOwnProperty(nestedKey)) { // "All clear Captain, the area is secure" } } } }

Arrays inside objects? Say no more

When objects have array properties, they are like burger boxes with fries in them ๐ŸŸ. Here's how to enjoy both:

for (let prop in objWithArrays) { const value = objWithArrays[prop]; if (Array.isArray(value)) { for (let item of value) { console.log(`Here is your array item: ${item}`); } } else { console.log(`Not an array, but still tasty: ${objWithArrays[prop]}`); } }

Extra joy? Alerts for specific nested properties ๐Ÿšจ:

for (let [name, messages] of Object.entries(objWithMessages)) { if (messages.your_msg) { alert(`Message for ${name}: ` + messages.your_msg); } if (messages.your_name) { console.info(`User name in message: ${messages.your_name}`); } }

Information highlighter, caught red-handed! ๐Ÿ’ก