JS calculates the length of an Object / Object

Posted by nrerup on Thu, 02 Apr 2020 08:38:38 +0200


July 31, 2016 22:02:40
  • 10288

In our daily development, objects are used frequently. It is very convenient for us to calculate the length of arrays, but how to calculate the length of objects?
If we have a library project with a group of books and authors, like the following:

  1. var bookAuthors = {  
  2.     "Farmer Giles of Ham""J.R.R. Tolkien",  
  3.     "Out of the Silent Planet""C.S. Lewis",  
  4.     "The Place of the Lion""Charles Williams",  
  5.     "Poetic Diction""Owen Barfield"  
  6. };  

We analyze the current requirements. We send data to an API, but the book length cannot exceed 100, so we need to calculate how many books there are in an object before sending data. So what do we always do? We may do this:

  1. function countProperties (obj) {  
  2.     var count = 0;  
  3.     for (var property in obj) {  
  4.         if (Object.prototype.hasOwnProperty.call(obj, property)) {  
  5.             count++;  
  6.         }  
  7.     }  
  8.     return count;  
  9. }  
  10.   
  11. var bookCount = countProperties(bookAuthors);  
  12.   
  13. // Outputs: 4  
  14. console.log(bookCount);  


This is possible, and fortunately Javascript provides a way to change the length of an object:

  1. var bookAuthors = {  
  2.     "Farmer Giles of Ham""J.R.R. Tolkien",  
  3.     "Out of the Silent Planet""C.S. Lewis",  
  4.     "The Place of the Lion""Charles Williams",  
  5.     "Poetic Diction""Owen Barfield"  
  6. };  
  7. var arr = Object.keys(bookAuthors);  
  8.   
  9. //Outputs: Array [ "Farmer Giles of Ham", "Out of the Silent Planet", "The Place of the Lion", "Poetic Diction" ]  
  10. console.log(arr);  
  11.   
  12. //Outputs: 4  
  13. console.log(arr.length);  

Let's use the keys method for arrays:

  1. var arr = ["zuojj""benjamin""www.zuojj.com"];  
  2.   
  3. //Outputs: ["0", "1", "2"]  
  4. console.log(Object.keys(arr));  
  5.   
  6. //Outputs: 3  
  7. console.log(arr.length);  

The Object.keys() method will return an array of attribute names of all enumerable properties of a given object. The order of attribute names in the array is the same as that of traversing the object using the for in loop (the main difference between the two is that for in will also traverse the enumerable properties an object inherits from its prototype chain).

Topics: Attribute Javascript