Method 1: Using the Object.keys() method: The Object.keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.
Syntax:
objectLength = Object.keys(exampleObject).length
Example:
<!DOCTYPE html> < html > < head > < title >Length of a JavaScript object</ title > </ head > < body > < h1 style = "color: green" >GeeksforGeeks</ h1 > < b >Length of a JavaScript object</ b > < p > exampleObject = { id: 1, name: 'Arun', age: 30 } </ p > < p > Click on the button to get the length of the object. </ p > < p > Length of the object is: < span class = "output" ></ span > </ p > < button onclick = "getObjectLength()" > Get object length </ button > < script > function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30 } // Using Object.keys() method to get length objectLenght = Object.keys(exampleObject).length; document.querySelector('.output').textContent = objectLenght; } </ script > </ body > </ html > |
Output:
- Before clicking the button:
- After clicking the button:
Method 2: Loop through all the fields of the object and check their property: The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its own property. This method can be used to check if each key is present in the object itself. The contents of the object are looped through and if the key is present, the total count of keys is incremented. This gives the length of the object.
Syntax:
var key, count = 0; // Check if every key has its own property for (key in exampleObject) { if (exampleObject.hasOwnProperty(key)) // If the key is found, add it to the total length count++; } objectLenght = count;
Example:
<!DOCTYPE html> < html > < head > < title >Length of a JavaScript object</ title > </ head > < body > < h1 style = "color: green" >GeeksforGeeks</ h1 > < b >Length of a JavaScript object</ b > < p > exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } </ p > < p > Click on the button to get the length of the object. </ p > < p > Length of the object is: < span class = "output" ></ span > </ p > < button onclick = "getObjectLength()" > Get object length </ button > < script > function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } var key, count = 0; // Check if every key has its own property for (key in exampleObject) { if (exampleObject.hasOwnProperty(key)) // If key is found, add it // to total length count++; } objectLenght = count; document.querySelector('.output').textContent = objectLenght; } </ script > </ body > </ html > |
Output:
- Before clicking the button:
- After clicking the button: