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] );
}
}
}
}
}
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
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