So I was working with a colleague who showed me how i could solve a particular problem: how to get a flat object into a nested object. The object properties are named in such a way that they can be sliced into their relevant key named and then nested. His solution works beautifully, but when I ran through his code myself later I couldn't understand how it works.
I'm essentially taking a excel worksheet and creating json from it but for argument sake i'll remove the excel parts and just add the example structure which comes out of the excel parser:
//Example data
var result = {
frame1.title: "heading",
frame1.division: "first",
frame1.data[0].month: "Jan",
frame1.data[0].value: "54",
}
function deepInsert (o, path, value) {
let next, cur = o
path.forEach((p,i) => {
next = cur[p]
if (i == path.length -1) {
cur[p] = value
} else {
if (!next) {
next = cur[p] = {}
}
cur = next
}
})
}
function processWorkbook () {
const result = json.map(item => {
var o = {foo: "bar"}
Object.keys(item).forEach(prop => {
deepInsert(o, prop.split('.'), item[prop])
console.log(JSON.stringify(o, 0, ' '));
})
return o
})
console.log(JSON.stringify(result, 0, ' '))
}
From what I can tell it looks like hes passing in 'o', which is a blank object, then the loop in the deepInsert function is assigning data to not the param, but the object in the calling function, because everytime through the loop, my console log shows more being added to the object.
I also don't understand this part: next = cur[p] = {}
. For some reason a triple assignment throws me an error in the chrome repl but not in that function? Im just so confused, any help would be great!