Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop json objects within object

I know this question has been asked a thousand times but I have not been able to find a solution that would help with the way I have structured my json object. It maybe that I have the structure wrong.

Here is my json:

check_styles = {
    'html':{
        'background-color':'rgb(0, 0, 0)',
        'color':'rgb(0, 0, 0)'
    },
    '#my-div':{
        'background-color':'rgb(0, 0, 0)'
    }
};

I want to loop over and get the values 'html', 'background-color', 'rgb(0, 0, 0)' then 'html', 'colour', 'rgb(0, 0, 0)' etc to send to a function.

Here is the loop so far but I have not been able to get the values of the object in the object. I don't think another loop is the answer.

function style_check(styleList)
{

    for (var key in styleList) {
        if (styleList.hasOwnProperty(key) ){
            console.log( "key:"+key+", val:"+styleList[key] );
        }
    }

}

****My Solution

After the 3 different perfectly valid solutions I have gone with a nested loop as it made sense to me with my limited knowledge of javascript.

function style_check(styleList)
{
    for (var selector in styleList) {
        if (styleList.hasOwnProperty(selector) ){
            for (var property in styleList[selector]) {
                if (styleList[selector].hasOwnProperty(property) ){
                    console.log( "selector:"+selector+", property:"+property+", value:"+styleList[selector][property] );
                }
            }
        }
    }
}
like image 823
Keith Power Avatar asked Aug 16 '26 19:08

Keith Power


1 Answers

Yes, a nested loop is the answer.

function style_check(styleList)
{
    for (var key in styleList) {
        if (styleList.hasOwnProperty(key) ){
            console.log( "key:"+key+", val:"+styleList[key] );
            var obj = styleList[key];
            for (var objkey in obj){
                if (obj.hasOwnProperty(objkey)){
                    console.log("key2:"+objkey+",val:"+obj[objkey]);
                }
            }
        }
    }
}

Check this fiddle

like image 70
RJM Avatar answered Aug 19 '26 11:08

RJM