Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print all values of a nested object

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?

like image 898
mrdaliri Avatar asked Apr 08 '15 13:04

mrdaliri


1 Answers

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/

like image 192
tymeJV Avatar answered Sep 30 '22 06:09

tymeJV