I believe you are almost there.
When comparing typeof val === “object”, please note that null
is also treated as a object type in Javascript. So please make sure you do a null check on your solution.
If you try to do Object.entries(null)
, it gives Uncaught TypeError: Cannot convert undefined or null to object
var loadedData = {
b: {x:1, c:3, d: [{x: null}]},
r: {e:[{s:[34]}], f:{t: 4}, g: [{rr: 2}]}
}
const keyValuePairFuncs = (obj) => {
if(!obj) return; // Added a null check for Uncaught TypeError: Cannot convert undefined or null to object
for (const [key, val] of Object.entries(obj)) {
console.log(`${key}: ${JSON.stringify(val)}`)
if (typeof val === "object") {
keyValuePairFuncs(val); // recursively call the function
}
}
}
keyValuePairFuncs(loadedData);
3
solved Recursively loop through object to display key/value pairs [duplicate]