How to get the length of an object inside an object in JS

Overview

We can get the length of an object within an object in JavaScript by using the different properties of an object. Here are the methods to get the number of properties present in an object:

  • We can use the Object.keys method to return an array with the object's own enumerable property names.
  • The keys array doesn't include the Symbols properties present in the object. To add this, we call the Object.getOwnPropertySymbols method that returns an array of all symbol properties found directly upon a given object.
  • Once we have the keys and the symbols array, we add the length property of the two arrays to get the number of properties present in the object.

Example

The code below demonstrates how to get the length of an object inside an object in JavaScript:

var numbers = {
num:{
one: 1,
two: 2,
three: 3,
[Symbol('four')]: 4
}
};
console.log("\nThe object is :", numbers);
let keys = Object.keys(numbers.num);
let symbols = Object.getOwnPropertySymbols(numbers.num);
console.log("\nThe keys of numbers.num :", keys);
console.log("The symbols of numbers.num :", symbols);
console.log("The length of keys : ", keys.length);
console.log("The length of symbols : ", symbols.length)
let length = keys.length + symbols.length;
console.log("\nThe length of the object is :", length);

Explanation

Lines 1-8: We create an object, numbers. This object has a property, num, that is also an object. Therefore, we can say that num is an object within another object, numbers.

Line 10: We print the numbers object.

Line 12: We use the Object.keys method to get the num property's own keys. This method returns an array. We store that array in the keys variable.

Line 13: We use the Object.getOwnPropertySymbols method to get the num property's own symbol properties. This method returns an array. We store that array in the symbols variable.

Line 15-16: We print the keys and symbols which we stored in the arrays before.

Line 17-18: We print the length of the keys and symbols arrays.

Line 21-23: We add the length of the keys and symbols arrays to get the length of the num object. In the end, we print the length of the num object.

Free Resources