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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With