jwolf jwolf - 2 months ago 19
HTML Question

Using recursion, how do you iterate over an object to produce HTML?

I am trying to sort an object of key:values recursively. It seems to work , at least to the console. The code takes the object and iterates over the key value pairs. If it finds another object it calls itself to iterate over that object. The problem I have is that the subsequent call doesn't seem to produce any html, but it does show the key value pairs in the console. This is my first attempt at recursion, I'm not sure if it's the way I'm declaring variables or if I'm missing something in how recursion works.

$(document).ready(function(){
let conditionReport = {
weekNo:"5",
laps:"8",
heat:"6",
feature:"9",
tireSize:
{lf:"15",lr:"16",rf:"16.5",rr:"17"},
airPressure:
{lf:"8",lr:"10",rf:"12",rr:"16"},
tireTemperature:
{lf:"9",lr:"11",rf:"13",rr:"15"},
suspensionAdjustment:
{lf:"4",lr:"5",rf:"6",rr:"7"},
engineRPM:"2000",
trackCondition:"4",
damage2car:"3",
suspensionAdjustment2:
{upper:
{lf:"4",lr:"5",rf:"6",rr:"7"},
lower:
{lf:"4",lr:"5",rf:"6",rr:"7"},
},
notes:"note 3"
}

s = x => document.getElementById(x);

const isObject = val => (typeof val === "object") ? true : false;

const getKeyValue = (obj) => {
let html = '<ul>';
for(let key in obj) {
let value = obj[key]
if(!isObject(value)){
//console.log(isObject(value));
console.log(key + ":" + value);
html += '<li>' + key + ":" + value + "</li>";
}
else{
if(isObject(value)){
//console.log(isObject(value));
console.log(key + "=>");
getKeyValue(value);
html += '<li>' + key + ":"+ "</li>";
}
}
}
html += "</ul>";
s('cards').innerHTML = html;
}

getKeyValue(conditionReport);

});

Answer Source

Use return values:

const getKeyValue = (obj) => {
    let html = '<ul>';
    for (let key in obj) {
        let value = obj[key]
        if (!isObject(value)) {
            html += '<li>' + key + ":" + value + "</li>";
        } else {
            var innerValue = getKeyValue(value);
//          ^^^^^^^^^^^^^^^^
            html += '<li>' + key + ":"+ innerValue + "</li>";
//                                      ^^^^^^^^^^
        }
    }
    html += "</ul>";
    return html;
//  ^^^^^^
}

Then do

s('cards').innerHTML = getKeyValue(conditionReport);