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 07, 2024

In JavaScript, you can use the JSON object to get the length of an object. One way to do this is by using the Object.keys() method, which returns an array containing the property names of the object. Then, you can use the length property of the array to get the number of keys in the object.

Here's an example of how to do this:

```javascript

let obj = {

key1: 'value1',

key2: 'value2',

key3: 'value3'

};

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

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

```

In this example, we have an object `obj` with three key-value pairs. We use `Object.keys(obj).length` to get the length of the object, which is 3.

Another way to get the length of an object is by using a for...in loop. This loop iterates over all enumerable properties of an object, including its own properties and properties inherited from its prototype chain. You can use this loop to count the number of properties in the object.

Here's an example of using a for...in loop to get the length of an object:

```javascript

let obj = {

key1: 'value1',

key2: 'value2',

key3: 'value3'

};

let length = 0;

for (let key in obj) {

if (obj.hasOwnProperty(key)) {

length++;

}

}

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

```

In this example, we initialize the `length` variable to 0 and then use a for...in loop to iterate over the keys of the object `obj`. We use the `hasOwnProperty` method to check if the key is a direct property of the object, and if it is, we increment the `length` variable.

These are two common ways to get the length of an object in JavaScript using JSON. Whether you prefer using the Object.keys() method or a for...in loop, both methods are effective in getting the length of an object and can be used in different scenarios depending on your specific use case.

Recommend