0

I want to be able to create subkeys if needed when assigning values to an object.

The thing is I get a JSON that can be having these values:

{
  "myKey": "Foobar",
  "myOtherKey.mySubkey.myOtherSubkey": "Bazboo"
}

Saying we want to inject the values to Node's global object, we would have the following:

global: {
  myKey: "Foobar",
  myOtherKey: {
    mySubkey: {
      myOtherSubkey: "Bazboo"
    }
  }
}

What I have at the moment is this :

function addGlobal (key, val) {
  if(~key.indexOf('.')) {
    let keys = key.split('.');
    let context = global;

    while(keys.length) {
        key = keys.shift();
        if(! (key in context)) {
            context[key] = {};
        }
        context = context[key]
    }
    context = val;
  }
  else {
    global[key] = val;
  }
}
Tripesdeporc
  • 94
  • 1
  • 1
  • 14

1 Answers1

-1

I have modified your logic to use recursive, please check it and let me know if you face any issues

var temp = {
  "myKey": "Foobar",
  "myOtherKey.mySubkey.myOtherSubkey": "Bazboo"
};
function test(){
  addGlobal('myKey','Foobar',global);
  addGlobal('myOtherKey.mySubkey.myOtherSubkey','Bazboo',global);
  document.getElementById("json").innerHTML = JSON.stringify(global, undefined, 2);
}
var global= {}
function addGlobal (key, val,temppp) { 
    var keys = key.split('.');
     if(keys.length==1){
       temppp[key]=val;
     }else{
  if(!temppp[keys[0]]){
     temppp[keys[0]]={};
  }
     var crrentObject= temppp[keys[0]];
  if(!crrentObject)
     crrentObject={};
         keys.splice(0, 1); 
        addGlobal(keys.join('.'),val,crrentObject)
     } 
}
<input type="button" value="click" onclick="test()">
Click test and check global object below 
<pre id="json"></pre>