Javascript:迭代对象的属性并将它们分配给新对象

时间:2013-08-14 11:56:09

标签: javascript

我有以下代码:

var self = this;
var test = function (name, properties) {
    self[name] = {
        prop1: "test1",
        prop2: "test2"
    };

    // some code here assigning properties object to self[name] object
};

test("myObj", { "prop3": "test3", "prop4": "test4" });

我需要完成的是将properties对象的内容分配给myObj,以便最终:

self["myObj"] = {
                prop1: "test1",
                prop2: "test2",
                prop3: "test3",
                prop4: "test3"

            };

3 个答案:

答案 0 :(得分:1)

jQuery有一种扩展名为jQuery.extend

的对象的方法

您可以查看jQuery如何实现此here

你会像这样使用它:

$.extend(self, { "prop3": "test3", "prop4": "test4" });

答案 1 :(得分:1)

如果对象很简单,你应该能够只添加一个foreach(如果没有,可能想要添加hasOwnProperty()检查)

foreach(var propertyKey in properties) {
    self[name][propertyKey] = properties[propertyKey];        
}

希望有所帮助!

答案 2 :(得分:1)

用此

替换函数中的注释行(//some code here assigning ...
for(var i in properties) self[name][i] = properties[i]

DEMO.

或更好

for(var i in properties) {
    if(properties.hasOwnProperty(i)) self[name][i] = properties[i];
}

DEMO>

相关问题