将值添加到jquery树对象

时间:2012-12-17 15:47:36

标签: javascript jquery

假设我有一个这样的对象。

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

我想要添加值的节点的路径,即:

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

如何以编程方式添加值?

3 个答案:

答案 0 :(得分:1)

试试这个:

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"}}

然而,您需要修复您的对象:

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

一个对象没有没有值的键,所以"obj1.1.1"必须有一个值,即使它是null

答案 1 :(得分:0)

假设这个对象

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

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

算法是:

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

或作为功能

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

答案 2 :(得分:0)

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

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

设置'test'的静态方法:

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

用newObj替换'test'的静态方法:

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