Manipulating multiple-level object parameters in Javascript

Asked

Viewed 98 times

1

I’m creating a service inside an angular application where I use a Value to generate a kind of session. thinking of the scenario:

angular.module("app.values", [])
    .value("a", {
        b : {
            c : {
                d: "joao"
            }
        }
    })
;

Thinking about the operation of a simple session basically I would have 2 functions: get, set. So far I’ve been able to think about the role of the guy get that stays that way:

function get(object, param) {
    var level = param.split("."), value = object;
    for (var i in level) 
      value = value[level[i]];
    return value;
}

The problem is that I’m not able to think of a method of doing the job set to manipulate only the specific value of an object, I have thought about it so far...

function(object, param, value){
    var level = param.split("."), object = object, value = value;
    for(var i = 0; i < level.length; i++){
        //e agora?????
    }
}

1 answer

1


function set(object, param, value) {
  var levels = param.split('.');
  var lastLevel = levels.pop();
  get(object, levels.join('.'))[lastLevel] = value;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.