I've been struggling with that problem for a few days. I have to transform an object into another object with a different structure.
from this:
{
"a1" : "key",
"a2" : {
"b1" : "key",
"b2" : {
"c1" : "key"
}
}
}
to this:
{
"key" : {
"a1" : null,
"a2" : [
{
"b1" : null,
},
{
"b2" : [
"c1" : null
]
}
]
}
}
For better understanding, a1, a2, b1, b3 etc. would represent css selectors. null will be the value applied to the node. But for now, this shouldn't matter.
My current (non working) function looks like this:
var json = {};
var obj = {};
function build(objA){
for(var a in objA){
var key = objA[a];
if(key instanceof Object){
obj = {}; obj[a] = key;
build(key);
} else {
json[key] = json[key] || {};
if(obj == undefined){
json[key][a] = null;
} else {
var p = firstKeyOf(obj);
var key = obj[p][a];
json[key][p] = json[key][p] || [];
var selector = {};
selector[a] = null;
json[key][p].push(selector);
}
}
}
}
which produces:
{
"key" : {
"a1" : null,
"a2" : [
{
"b1" : null
}
],
"b2" : [
{
"c1" : null
}
]
}
}
What did i miss? I appreciate any help, thanks!
build()andbuildsub(), where the former calls the latter, and the latter is recursive (calls itself). I'm guessing your currentbuild()would then be fine except that the current recursive call would instead callbuildsub(), but I'm not sure.