see the length of nested objects | javascript

PHOTO EMBED

Thu May 02 2024 06:02:09 GMT+0000 (Coordinated Universal Time)

Saved by @codejck #javascript

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
content_copyCOPY