function calculateLength(obj) { let length = 0; for (const key in obj) { if (typeof obj[key] === "object") { length += calculateLength(obj[key]); } else { length++; } } return length; } const obj = { name: "John Doe", age: 30, occupation: "Software Engineer", address: { street: "123 Main Street", city: "San Francisco", state: "CA", zip: "94105", }, }; const length = calculateLength(obj); console.log(length); // 6
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