Count properties in javascript object

JavaScript Program to Count the Number of Keys/Properties in an Object

To understand this example, you should have the knowledge of the following JavaScript programming topics:

Example 1: Count the Number of Key in an Object Using for. in

// program to count the number of keys/properties in an object const student = < name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], >; let count = 0; // loop through each key/value for(let key in student) < // increase the count ++count; >console.log(count);

The above program counts the number of keys/properties in an object using the for. in loop.

The count variable is initially 0. Then, the for. in loop increases the count by 1 for every key/value in an object.

Note: While using the for. in loop, it will also count inherited properties.

const student = < name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], >; const person = < gender: 'male' >student.__proto__ = person; let count = 0; for(let key in student) < // increase the count ++count; >console.log(count); // 4

If you only want to loop through the object’s own property, you can use the hasOwnProperty() method.

if (student.hasOwnProperty(key))

Example 2: Count the Number of Key in an Object Using Object.key()

// program to count the number of keys/properties in an object const student = < name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], >; // count the key/value const result = Object.keys(student).length; console.log(result);

In the above program, the Object.keys() method and the length property are used to count the number of keys in an object.

The Object.keys() method returns an array of a given object’s own enumerable property names i.e. [«name», «age», «hobbies»] .

The length property returns the length of the array.

Источник

How to Count the Number of Properties in a JavaScript Object

Learn how to count the number of properties in a JavaScript object, with two different methods.

To count the number of JavaScript object properties, you can either use:

Count object properties with a for loop

Here’s a JavaScript object called dog :

const dog =  name: "Naya", age: 2, color: "black", Breed: "Rottweiler mix", >

To count the number of object properties in dog , let’s first declare a variable called count and give it a start value of 0 :

Now we need to loop through the dog object and for each property we come across we add one (+ 1) to the count variable:

for (let properties in dog)  count = count + 1 >

Now try printing the result by using console.log() :

console.log(count) // Result: 4

If you wrote the code correctly, you should get 4 .

Count object properties with Object.keys()

You can also use JavaScript’s Object.keys() method to count all the enumerable properties (more about that in a sec) on an object.

Let’s reuse the dog object from before, but now we pass the dog object to Object.keys() and calculate its length with the length property:

const dog =  name: "Naya", age: 2, color: "black", Breed: "Rottweiler mix", > let count = Object.keys(dog).length console.log(count) // Result: 4

As you can see, the result is the same. Or is it?

Yes and no. It depends on the context.

The difference between using a for loop and Object.keys() is:

  • The for loop counts both the properties of the object (here, dog ) and any properties that might be linked to the object outside of it.
  • By default, the Object.keys() method only counts (enumerates) the object’s (own) enumerate properties — not linked properties.

Enumeration is another word for counting.

What do I mean with “linked properties”?

Let’s take the same Object.keys() example from before, but this time we link the dog object to an object called animal by using the _proto_ property:

// New object let animal =  fourLegs: true, > const dog =  name: "Naya", age: 2, color: "black", Breed: "Rottweiler mix", > // Link dog object to animal object dog.__proto__ = animal var count = Object.keys(dog).length console.log(count) // Result: 4

Why is the result 4, when the total number of properties of dog and animal is 5, and we just linked them together and counted them?

Because we’re using Object.keys() which only counts its own (enumerable) properties, not linked properties. Therefore the fourLegs property from the animal object doesn’t get counted in the example above.

Now let’s try another example, but this time we use the for loop to count properties:

const animal =  fourLegs: true, > const dog =  name: "Naya", age: 2, color: "black", Breed: "Rottweiler mix", > // Link dog object to animal object dog.__proto__ = animal let count = 0 for (properties in dog)  count = count + 1 > console.log(count) // Result: 5

Now we’re getting all 5 properties, because unlike Object.keys() when we use a for loop we count every property of an object, including linked object properties.

As you can see, it matters which approach you use.

  • There are two ways to count the number of properties in an object. You can use a for loop or the Object.keys() method.
  • Use a for loop if you wish to include any linked object properties in your property count.
  • Use Object.keys() if you only wish to count enumerable properties (the object’s own).

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Источник

How to Count the Number of Properties in a JavaScript Object: Methods and Examples

Learn how to count the number of properties in a JavaScript object using different methods such as for loops, Object.keys(), and Object.entries(), along with examples and tips for efficient coding.

As a developer, you know that JavaScript objects are a fundamental part of the language, and it is common to need to retrieve information about them, such as the number of properties they contain. In this blog post, we will explore several methods for counting the number of properties in a javascript object , each with its own advantages and disadvantages. We will also provide examples of how they can be used in practice.

Using a for loop to count properties

One method for counting the number of properties in a JavaScript object is to use a for loop to iterate through the object and increment a counter variable for each property that is found. This method is straightforward and can be used with any object, but it can be less efficient than other methods for larger objects.

Here’s an example of how to use a for loop to count properties in an object:

let obj = ; let count = 0; for(let prop in obj) < if(obj.hasOwnProperty(prop)) < count++; >> console.log(count); // Output: 3 

In this example, we create an object with three properties: a, b, and c. We then use a for loop to iterate through the object and check whether each property belongs to the object itself or to its prototype chain using the hasOwnProperty() method. If the property belongs to the object itself, we increment the count variable. Finally, we log the count variable to the console, which outputs the number of properties in the object.

Using Object.keys() to count properties

Another method for counting properties in a JavaScript object is to use the Object.keys() method , which returns an array of the object’s property names. The length of this array can be used to determine the number of properties in the object.

Here’s an example of how to use Object.keys() to count properties in an object:

let obj = ; let count = Object.keys(obj).length; console.log(count); // Output: 3 

In this example, we create an object with three properties: a, b, and c. We then use the Object.keys() method to get an array of the object’s property names and store the length of this array in the count variable. Finally, we log the count variable to the console, which outputs the number of properties in the object.

Using Object.entries() to count properties

The Object.entries() method returns an array of the object’s key-value pairs, which can be used to determine the number of properties in the object. The length of this array can be used to determine the number of properties in the object.

Here’s an example of how to use Object.entries() to count properties in an object:

let obj = ; let count = Object.entries(obj).length; console.log(count); // Output: 3 

In this example, we create an object with three properties: a, b, and c. We then use the Object.entries() method to get an array of the object’s key-value pairs and store the length of this array in the count variable. Finally, we log the count variable to the console, which outputs the number of properties in the object.

Considering enumerable properties

When counting the number of properties in a JavaScript object, it is important to only consider the object’s own enumerable properties. To do this, the hasOwnProperty() method can be used to check whether a property belongs to the object itself or to its prototype chain.

Here’s an example of how to use hasOwnProperty() to count properties in an object:

let obj = ; let count = 0; for(let prop in obj) < if(obj.hasOwnProperty(prop)) < count++; >> console.log(count); // Output: 3 

In this example, we create an object with three properties: a, b, and c. We then use a for loop to iterate through the object and check whether each property belongs to the object itself or to its prototype chain using the hasOwnProperty() method. If the property belongs to the object itself, we increment the count variable. Finally, we log the count variable to the console, which outputs the number of properties in the object.

Additional code samples for counting the number of properties in a JavaScript object

In Javascript , in particular, get amount of items in object js code sample

Conclusion

In this blog post, we have explored several methods for counting the number of properties in a JavaScript object, including using a for loop, Object.keys(), and Object.entries(). We have also discussed the importance of considering enumerable properties and provided examples of how to do this using the hasOwnProperty() method. By using these methods, developers can more easily retrieve information about JavaScript objects and make more informed decisions about how to work with them in their code.

Источник

How to Count the Number of Properties of the JavaScript Object

Join the DZone community and get the full member experience.

While working with JavaScript, I come across a requirement to count a number of properties in a JavaScript object. I found two ways to find the number of properties in an object. They are as follows:

Consider an object, «cat,» as demonstrated below:

You can find a number of properties by iterating in a for loop and update counter, as shown in the below listing:

let count = 0; for (var c in cat) < count = count + 1; >console.log(count);// 2

Above code will print «2» as the output.

The above approach not only prints the object’s own enumerable properties, but it also prints properties of objects to which it is linked. To further understand it, let us consider the below listing:

var animal = < canRun: true >var cat = < name: 'foo', age: 9 >cat.__proto__ = animal;

There are two objects, cat and animal , and the cat object is linked to an animal object using the __proto__ property. Now, when you use a for loop to iterate and count a number of properties, it will also count the enumerable properties of the animal object. Therefore, the code listing below will print «3.»

var animal = < canRun: true >var cat = < name: 'foo', age: 9 >cat.__proto__ = animal; let count = 0; for (var c in cat) < count = count + 1; >console.log(count);// 3

A JavaScript for loop will iterate through all the linked properties of the object.

To count the object’s own enumerable properties, you may consider using another approach, Object.keys(), which only enumerates the object’s own enumerable properties. It does not enumerate the object’s linked properties.

Moving forward, let us again consider the cat object which is linked to animal object and count the number of properties using Object.keys :

var animal = < canRun: true >var cat = < name: 'foo', age: 9 >cat.__proto__ = animal; var count = Object.keys(cat).length; console.log(count);

Now you will get «2» printed as the output.

Object.keys only enumerates the object’s own enumerable properties.

If the object’s property enumerable is set to false, then it is not a member of the Object.keys array. Let us again consider the cat object and set its name property enumerable to false.

var cat = < name: 'foo', age: 9 >Object.defineProperty(cat, 'name', < enumerable: false >);

Now, when you use Object.keys to find a number of properties, it will count only one.

var count = Object.keys(cat).length; console.log(count); // print 1

In closing, these are the two ways that you can use to find the number of properties in a JavaScript object.

Published at DZone with permission of Dhananjay Kumar , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Читайте также:  Javascript games for android
Оцените статью