Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all properties of an object?

Tags:

How to get all properties of an object using reflection in JavaScript?

like image 694
IAdapter Avatar asked Dec 26 '11 20:12

IAdapter


People also ask

How can you get list of all properties in an object?

getOwnPropertyNames() The Object. getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

How do you get all the values of an object?

values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.

How do I print all properties of an object?

First way to print all properties of person object is by using Object. keys() method. In this method we pass the person object to Object. keys() as an argument.


2 Answers

Loop through the object and take every key that belongs to it and is not a function:

var properties = []; for(var key in obj) {     if(obj.hasOwnProperty(key) && typeof obj[key] !== 'function') {         properties.push(key);     } } 
like image 161
Daff Avatar answered Sep 19 '22 05:09

Daff


In modern browsers, to get all property names (not just enumerable properties), you'd use Object.getOwnPropertyNames...

var props = Object.getOwnPropertyNames(my_object) 

If you don't want enumerable properties, you'd use Object.keys...

var props = Object.keys(my_object) 
like image 28
user1106925 Avatar answered Sep 18 '22 05:09

user1106925