Given I have a javascript object, is there a way to iterate over all the primitive subproperties?
For instance, if I have an object
{
foo: 17,
bar: {
a: 2,
b: 7
}
}
I would like to iterate over foo, bar.a, and bar.b.
Please keep in mind I prefer to iterate over Object.keys() rather than using a for/in loop, although I'm sure I could translate any for/in loop responses into an Object.keys() iteration.
Given I have a javascript object, is there a way to iterate over all the primitive subproperties?
For instance, if I have an object
{
foo: 17,
bar: {
a: 2,
b: 7
}
}
I would like to iterate over foo, bar.a, and bar.b.
Please keep in mind I prefer to iterate over Object.keys() rather than using a for/in loop, although I'm sure I could translate any for/in loop responses into an Object.keys() iteration.
Share Improve this question asked Jan 25, 2013 at 16:17 ferson2020ferson2020 3,3753 gold badges19 silver badges26 bronze badges 5- 2 Have you tried anything yet? – phant0m Commented Jan 25, 2013 at 16:18
-
What you are looking for is called
Object Reflection
– Joe Commented Jan 25, 2013 at 16:20 - I could right a function that recursively checks all objects for properties and returns an array of primitive properties, but I was wondering if there was a standard or built-in way of doing it. – ferson2020 Commented Jan 25, 2013 at 16:22
- @Joe Is that a concept, or an actual function? Could you give me a code example please? – ferson2020 Commented Jan 25, 2013 at 16:25
- 1 There is no built-in support for recursive enumeration of object properties in JavaScript. – apsillers Commented Jan 25, 2013 at 16:36
2 Answers
Reset to default 7You can use a recursive function like this:
var x = {
foo: 17,
bar: {
a: 2,
b: 7
}
}
function parseObject(something) {
var keys = Object.keys(something);
for (var i = 0; i < keys.length; i++) {
if (typeof something[keys[i]] === 'object') parseObject(something[keys[i]])
else console.log(keys[i] + " : " + something[keys[i]]);
}
}
parseObject(x);
Which generates the output:
foo : 17
a : 2
b : 7
A note on this function. It recurses over anything that is an object. For instance, if you had an array in the object, you would get separate lines for each item in the array.
So for the following object:
var x = {
foo: 17,
bar: {
a: 2,
b: 7
},
foobar: [1,2,3]
}
The output would appear:
foo : 17
a : 2
b : 7
0 : 1
1 : 2
2 : 3
There are obviously ways to handle this, but you will need to tailor the function to meet your requirements.
Update: This is how you can do it (taken from one of the links below):
for (var key in validation_messages) {
var obj = validation_messages[key];
for (var prop in obj) {
alert(prop + " = " + obj[prop]);
}
}
This is a possible duplicate of :
Iterate through object properties
How to Loop through plain JavaScript object with objects as members?
you can find your answer in the above posts.