将对象插入未知对象路径

时间:2014-04-29 16:18:29

标签: javascript jquery html5 object

我想将一个对象插入到一个有点预定义的对象中:

var obj = {
    "scripts": {
        "libs":{}
    },
    "plugins":{}
}

//....

function addobj(path, obj){

    console.log(path); // Object {libs: Object}..
    path.push(obj); // TypeError: undefined is not a function

}

// Test cases:
addobj(obj["scripts"],{"test":{}});

console.log(obj);

但是发生错误:TypeError: undefined is not a function为什么会发生这种情况?

http://jsfiddle.net/Qn3Tb/

4 个答案:

答案 0 :(得分:1)

使用jQuery,您可以使用$.extend()

demo

$.extend(path,obj);

答案 1 :(得分:0)

你不能.push到一个对象上。 Object是键值存储,因此您需要为要存储在父对象上的对象(值)分配键。你如何实现这个是另一个问题,但这样的事情可能有用:

function addobj(path, obj, key) {
    path[key || "unnamed"] = obj;
}

如果您想将libs添加到scripts,请执行以下操作:

addobj(script, libs, "libs");

但是考虑到这个addobj方法实际上做了什么,我的建议是完全放弃抽象,不需要它。

答案 2 :(得分:0)

为什么不简单地做

function addProp(prop, value, targetObject){
    targetObject[prop] = value;
}

addProp('scripts', { test:{}}, obj);

根据您的问题,您可以使用此功能定位特定属性:

var obj = {
    "scripts": {
        "libs":{
            "labs": {
                foo: 1
            }
        }
    },
    "plugins":{}
};

function setPropByString(obj, propString, value) {
    if (!propString)
        return obj;

    var prop, props = propString.split('.');

    for (var i = 0, iLen = props.length - 1; i < iLen; i++) {
        prop = props[i];

        var candidate = obj[prop];
        if (candidate !== undefined) {
            obj = candidate;
        } else {
            break;
        }
    }

    obj[props[i]] = value;
}

setPropByString(obj, 'scripts.libs.labs', { something: 1 });

console.log(obj);

请注意,这将覆盖现有道具。因此,使用像@A.Wolff建议的jQuery扩展更容易。

http://jsfiddle.net/Mn45R/

答案 3 :(得分:0)

你不能以问题中提到的方式做到这一点。

我相信你应该创建一个函数,比如

function Node(key) {
    var currentNode = this;

    this.getKey = function() {
        return key;
    };

    var children = [];

    this.addNode(childKey) {
        children[children.length] = new Node(childKey);
    }

    this.search(searchKey) {
        if (searchKey === key) {
            return currentNode;
        }
        for (var childIndex in children) {
            var searchResult = children[childIndex].search(searchKey);
            if (!!searchResult) {
                return searchResult;
            }
        }
        return null;
    }
}

您可以这样创建root:

var root = new Node();

您可以通过这种方式将子项添加到根目录:

root.addNode("scripts");

此函数可用于将某个节点添加到具有密钥的另一个节点

function addNodeToTree(tree, key, newKey) {
    var node = tree.search(key);
    if (!!node) {
        node.addNode(new Node(newKey));
        return true;
    }
    return false;
}

最后,您可以添加如下节点:

addNodeToTree(root, "scripts", "test");