The Object.keys() method returns an array of object properties. For example, I have an array with few properties in it.
<script>
var birds = {
Name: 'Bald Eagle',
Type: 'Hawk',
ScientificName: 'Haliaeetus Leucocephalus'
}
console.log(Object.keys(birds));
</script>
The Output in your browser’s console would look like this.
👉 Remove duplicates in a JavaScript array using ES6 Set and from() function
It shows you all the properties with its keys (0, 1, …) and names. The above image also shows the length of the object (that is 3) at the end.
In your script you can add the length property to the Object.keys() method to get the length of the defined object.
console.log(Object.keys(birds).length);
Get the Length of a String Object
You can use the above method on a variety of objects. Now let’s apply this method to a String object.
<script>
var student = new String('Arun Banik');
document.write(Object.keys(student).length);
</script>
A String Object is created using the new operator. Like the array object above, I am using the length property of Object.keys() method to get the length of the string object. The output or the result would be 10.
Note: Alternatively, you can use student.length and this too will return 10. Learn more about how to find the length of a String using JavaScript
Getting the Length using Object Constructor
Object constructors in JavaScript are special functions to create objects. For example, I have defined a constructor and referred it as birds with some properties like name, type etc.
var bird = new Object() // its an object constructor.
bird.name = 'Eurasian Collared-Dove';
bird.type = 'Dove';
To get the length of the object, I’ll again use Object.key().length.
console.log(Object.keys(bird).length);
The output would be 2, since I have defined two properties to the object. Add few more properties to the object and get the length.