How to get object length in JavaScript | Code

  • by

Use the Object keys method to get object length in JavaScript. You can also find the length of the values inside the object.

var size = Object.keys(myObj).length;

How to get object length in JavaScript

A simple example code gets the keys as an array using Object.keys, and takes the length of that array:

<!DOCTYPE html>
<html>
<body>

  <script>
    const obj = {
      namespace: {
        key1: 'whatever1',
        key2: 'whatever2',
      }
    }

    const keys = Object.keys(obj.namespace) 
    const keysLength = keys.length

    console.log(keys)
    console.log(keysLength)
  </script>

</body>
</html> 

Output:

How to get object length in JavaScript

Another example

Find the size of the object (i.e total number of attributes in the object) like this:

namelist = { "name":"xyz", "version":"1.0.0" }
var size = Object.keys(namelist).length;
console.log(size); // 2

For getting the size of the value of name attribute

console.log(namelist.name.length) // 3

For getting the size of the value of version attribute.

console.log(namelist.version.length) // 5

Do comment if you have any doubts or suggestions on this Js Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.