Skip to content Skip to sidebar Skip to footer

Adding A Value To A Jquery Tree Object

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.

Solution 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.


Solution 2:

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']);

Solution 3:

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;

Post a Comment for "Adding A Value To A Jquery Tree Object"