In JavaScript, obtaining the length or number of properties within an object can be achieved through several methods.
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;
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;
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!