0

Suppose I have an object like that.

var t = {
    "obj1": {
        "obj1.1": "test",
        "obj1.2": {
            "obj1.1.1": null, // <-- "obj1.1.1" has to have a value.
            "obj1.1.2": "test"
        }
    }
};

And a path to the node where I'd like to add a value, i.e.:

var path = ['obj1', 'obj1.1', 'test'];

How do I add the value programmatically?

3
  • Um, you object is messed up. Don't you want arrays? "obj1.2" : [] Commented Dec 17, 2012 at 15:49
  • which value and where you want to add it ? Commented Dec 17, 2012 at 15:50
  • 1
    your object as defined is wrong. Please post the real code Commented Dec 17, 2012 at 15:52

3 Answers 3

1

Try this:

function setDeepValue(obj, value, path) {
    if(path.length > 1){
        var p=path.shift();
        if(obj[p]==null || typeof obj[p]!== 'object'){
            obj[p] = {};
        }
        setDeepValue(obj[p], value, path);
    }else{
        obj[path[0]] = value;
    }
}

var obj = {};
var path = ['obj1', 'obj1.1'];
setDeepValue(obj, 'test', path);
console.log(obj); // {"obj1":{"obj1.1":"test"}}

You will however need to fix your object:

var t = {
    "obj1": {
        "obj1.1": "test",
        "obj1.2": {
            "obj1.1.1": null, // <-- "obj1.1.1" has to have a value.
            "obj1.1.2": "test"
        }
    }
};

A object can't have a key without a value, so "obj1.1.1" will have to have a value, even if it's null.

Sign up to request clarification or add additional context in comments.

Comments

0

Supposing this object

var obj = {
      "obj1" : {
          "obj1.1" : "",
          "obj1.2" : {
             "obj1.1.1" : "",
             "obj1.1.2" : ""
             }
          }
      }

var path = ['obj1', 'obj1.1', 'test'];

the algorithm is:

var el = obj;
for(var i = 0; i < path.length-2; i++) {
     el = el[path[i]]; 
}
el[path[i]] = path[i+1];

or as function

function setpath(obj,path) {
    var el = obj;
    for(var i = 0; i < path.length-2; i++) {
        console.log(i+"="+path[i]);
         el = el[path[i]]; 
    }
    el[path[i]] = path[i+1];
    console.log(el);
}

setpath(obj,['obj1', 'obj1.1', 'test']);

Comments

0
var tree = {
    "obj1": {
        "obj1.1": "test",
        "obj1.2": {
            "obj1.1.1": null,
            "obj1.1.2": "test"
        }
    }
};

var path = ['obj1', 'obj1.1', 'test'];

A static way of setting 'test':

tree[path[0]][path[1]] = path[2];

A static way of replacing 'test' with newObj:

var newObj = { ... };
tree[path[0]][path[1]][path[2]] = newObj;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.