Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
44
rated 0 times [  49] [ 5]  / answers: 1 / hits: 20769  / 9 Years ago, wed, april 8, 2015, 12:00:00

There is a nested object like that:



var conversation = {
'John': {
1: 'Test message 1',
2: 'Test message 2',
'Reply': {
3: 'Test message 3',
4: 'Test message 4'
}
},
'Jack': {
5: 'Test message 5',
6: 'Test message 6'
}
};


I need to get all final values, so for that example, it is:



Test message 1
Test message 2
Test message 3
Test message 4
Test message 5
Test message 6


How to iterate over the object? Is there any built-in function in jQuery or JavaScript?


More From » jquery

 Answers
4

You can use some recursion to check to see if the key being iterated over is an object or not, then print:



function printValues(obj) {
for (var key in obj) {
if (typeof obj[key] === object) {
printValues(obj[key]);
} else {
console.log(obj[key]);
}
}
}

printValues(conversation);


Demo: http://jsfiddle.net/c7th1t8r/


[#67151] Monday, April 6, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dorab

Total Points: 22
Total Questions: 106
Total Answers: 99

Location: El Salvador
Member since Fri, May 8, 2020
4 Years ago
;