Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Get Length of Object in JavaScript

Oct 06, 2024

In JavaScript, you can use the JSON object to get the length of another object. The length of an object refers to the number of properties it has. This can be useful for iterating through the properties of an object or checking if it’s empty.

To get the length of an object, you can use the Object.keys() method to return an array of the object's properties, and then use the length property of the array to get the number of properties. Here’s an example:

```javascript

let myObject = {

name: 'John',

age: 30,

gender: 'male'

};

let length = Object.keys(myObject).length;

console.log(length); // Output: 3

```

In this example, we use Object.keys() to get an array of the keys in the myObject object, and then we use the length property to get the number of keys in the array, which is the length of the object.

You can also create a function to get the length of an object, which can be reusable for different objects:

```javascript

function getObjectLength(obj) {

return Object.keys(obj).length;

}

let length = getObjectLength(myObject);

console.log(length); // Output: 3

```

This function takes an object as an argument, uses Object.keys() to get an array of its keys, and returns the length of the array, which is the length of the object.

Keep in mind that this method only counts the enumerable own properties of an object, and does not include properties from the object's prototype chain.

In summary, you can use the JSON object’s Object.keys() method to get an array of an object's properties, and then use the length property of the array to get the length of the object. This can be useful for various tasks such as iterating through properties, checking if an object is empty, or performing other operations based on the number of properties in an object.

Recommend