0

I've read this existing question on stackoverflow.

My target is to set a property on a "nested Property and set a new Value (without eval!):

What i have is a dynamic string as example : “A.B.C

And a JSON Object:

var obj ={
    A: {
        B: {
            C: 23
            C1: {}
            }   
    }
}

Now i want to access this property and set it:

If the string has a fixed amount of properties i can just write:

obj[prop1][prop2][prop3] = 42

What would be the way to make this dynamic, so when passing “A.B” the object at B is replaced?

MemLeak
  • 4,456
  • 4
  • 45
  • 84

1 Answers1

0

Something like this will work..

var str = "A.B.C";
var obj ={
  A: {
    B: {
      C: 23,
      C1: {}
    }   
  }
};
updateObj(obj,str,10);

function updateObj(obj,str,val){
  var tok = str.split(".");
  var update = function(obj, index){
    if (index < tok.length){
      if ( !obj.hasOwnProperty(tok[index])){  
        obj[tok[index]] = {};  
      } 
      if (index == tok.length-1){
        obj[tok[index]] = val;
      }
      update(obj[tok[index]],++index);
    }

  }
  update(obj,0);
}

console.log(obj);
Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40