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
Release: 2024-12-20 11:58:10
Original
892 people have browsed it

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;
Copy after login

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;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template