Find the length of a JavaScript object
In this article, we will learn how to find the length of a JavaScript object. As we know in object there is no built-in function for finding the length of the object. Therefore, we use different approaches for finding the object length.
Below are the following approaches:
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: This example shows the use of the above-explained approach.
Javascript
function getObjectLength() {
exampleObject = {
id: 1,
name: 'Arun' ,
age: 30
}
objectLength = Object.keys(exampleObject).length;
console.log(objectLength);
}
getObjectLength();
|
The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its 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:
let 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: This example shows the use of the above-explained approach.
Javascript
function getObjectLength() {
exampleObject = {
id: 1,
name: 'Arun' ,
age: 30,
department: 'sales'
}
let key, count = 0;
for (key in exampleObject) {
if (exampleObject.hasOwnProperty(key))
count++;
}
objectLength = count;
console.log(objectLength);
}
getObjectLength();
|
JavaScript Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter. The ordering of the properties is the same as that given by looping over the property values of the object manually.
Syntax:
Object.entries(obj)
Example: This example shows the use of the above-explained approach.
Javascript
function getObjectLength() {
exampleObject = {
id: 1,
name: 'Arun' ,
age: 30,
department: 'sales'
}
const objectLength = Object.entries(exampleObject).length;
console.log(objectLength);
}
getObjectLength();
|
Lodash _.size() method is used to get the size of the given object or array.
Example: This example shows the use of the above-explained approach.
Javascript
const _ = require( "lodash" );
let gfg = _.size({ 'p' : 1, 'q' : 2, 'r' : 5 });
console.log(gfg);
|
Output:
3
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Last Updated :
29 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...