0

How to check in javascript how many direct properties object has? I want to know amount of direct properties in one object, not in prototypes chain. Is there any method to do so?

daniel098
  • 99
  • 8

2 Answers2

0

You can generate an array of prperties and then take the length

var x = {
    x1 : 1,
    x2 : 2,
    x3 : 3,
    x4 : 4
};
console.log(Object.keys(x).length); // => 4
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
0

It depends on which properties you'd like to measure. Consider the following scenario:

const array = ["some", "values", "here"];

Object.keys

Object.keys returns an array of all enumerable properties that reside directly on the object (i.e. the prototype chain will not be checked).

Object.keys(array); // ["0", "1", "2"]

Object.getOwnPropertyNames

Object.getOwnPropertyNames returns an array of all enumerable and non-enumerable properties that reside directly on the object (i.e. the prototype chain will not be checked).

Object.keys(array); // ["0", "1", "2", "length"]

for…in loop

Using a for…in loop, you can iterate over all enumerable properties in an object including its prototype chain. In this scenario, this happens to be analogous to Object.keys, but this will not hold anymore once you're dealing with prototype chains.

for (const property in array) {
    console.log(property); // "0", "1", "2"
}

Determining how many properties an object has would then be as simple as either accessing .length on the resulting arrays or incrementing a property counter in the for…in loop.

Chiru
  • 3,661
  • 1
  • 20
  • 30