Home >Web Front-end >JS Tutorial >How to Count the Properties in a JavaScript Object?

How to Count the Properties in a JavaScript Object?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 11:58:10973browse

How to Count the Properties in a JavaScript Object?

Count Properties in a JavaScript Object

In JavaScript, obtaining the length or number of properties within an object can be achieved through several methods.

Object.keys() Method

For browsers supporting ES5 and above, including IE9 , the Object.keys() method offers a straightforward solution. It returns an array containing the keys of the object, and its length can be determined as follows:

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

const size = Object.keys(myObject).length;

Object.getOwnPropertyNames() Method

Another viable option is the Object.getOwnPropertyNames() method, which provides a list of property names in the object, excluding any inherited properties from the prototype chain:

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

const size = Object.getOwnPropertyNames(myObject).length;

Caution with Symbol Properties

However, it's important to note that objects can possess symbolic properties, which are not returned by either Object.keys() or Object.getOwnPropertyNames(). To account for this, the Object.getOwnPropertySymbols() method can be employed:

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

const symbolProps = Object.getOwnPropertySymbols(myObject);
const totalSize = Object.keys(myObject).length + symbolProps.length;

The above is the detailed content of How to Count the Properties in a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn