Need some help over here. Been bashing my head against a piece of code for a while now, but I can't wrap my head around it. Slowly trying to learn JavaScript, and trying to handle a piece of JSON data.
The JSON data is as follows. (simple example, more nesting going to happen at some point)
{
"div": {
"attr-id": "josh",
"div": {
"attr-id": "greg"
}
}
}
(So far so good, right?) Well, now I'm trying to make this into HTML. First I did some for loops, I tried using "classes", nested functions, etcSo I figured a recursive function would be suitable. Oh, yes, let me get right on that! head explodes
I've been trying various functions, trying to find something as lean and mean as possible. The theory is:
Send parsed JSON to function. Function finds first property. If property value is an object then get property key to be used as value for a document.createElement(v). Else if property value is a string, that means there's an "attr" present. And we need to apply this to our element. However, what if the element isn't there yet? here's when my brain has starts to speed wobble). Anyway if the key value is an object, we would want to call the function again, this time supplying this data. And also, since we're handling elements. We'd want to append this outcome to our previous element. Eh..
I've discarded so much code, and I'm having a hard time wrapping my head around recursion, or simple the laws of javascript. I haven't gotten further than this I'm afraid and this code doesn't even work.
function recurseYou(obj) {
for(var key in obj) {
//probably a safer way testing than typeof = string
//but this'll have to do for now
if(typeof obj[key] != 'string'){
//create a new element
var el = document.createElement((key.split("."))[0]);
//append the return of the function using the
//current key value
el.appendChild(recurseYou(obj[key]));
} else {
// do stuff to string
}
}
return el;
}
Anyway, any pointers, tips or help very appreciated. But please keep it to JavaScript only, I'm not interested in solutions using libraries at this point!