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?
-
Yes there is a method to do so !! – kevin ternet Jul 26 '16 at 21:28
-
1Yes it's called [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys). *Note:* I'm sure there is a duplicate for this question, I'll see if I can find it. – Spencer Wieczorek Jul 26 '16 at 21:29
-
@Spencer Wieczorek thank you very much! It's what I was looking for. – daniel098 Jul 26 '16 at 21:32
2 Answers
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

- 4,514
- 2
- 19
- 27
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.

- 3,661
- 1
- 20
- 30