在JavaScript中合并两个对象

时间:2012-07-04 06:06:31

标签: javascript associative-array

我有两个JavaScript对象:

var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes2 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};

我有什么方法可以将两个对象合并为一个具有两个子对象(关联数组)的对象?我想循环throgh它,每次得到一组属性?

由于

3 个答案:

答案 0 :(得分:3)

是的,那些不是数组,但你可以有对象数组,我想你要找的是:

var attributes = [
                  {
                   "type": "text/css", 
                   "rel": "stylesheet",
                   "href": baseUrl + "Styles/HtmlLibrary.css"      
                  },
                  {
                   "type": "text/css",
                   "rel": "stylesheet",
                   "href": baseUrl + "Styles/jquery.contextMenu.css"       
                  }];

答案 1 :(得分:3)

是的,你可以轻松地做到这一点: -

var baseUrl="www.google.com" // Base URL just for the sake of program.
var attributes = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};
var k=[];
k.push(attributes);
k.push(attributes1)

    //Since K has both the associative arrays now you can refer using
    for(var i=0;i<k.length;i++)
        {
        console.log(k[i].type+" "+k[i].rel+" "+k[i].href)

        }

这是小提琴网址http://jsfiddle.net/HSdJh/1/

答案 2 :(得分:1)

var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes2 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};

var combined = {};

combined.attributes1 = attributes1;
combined.attributes2 = attributes2;


for(var attribute in combined){

    if(combined.hasOwnProperty(attribute)){
        console.log(attribute);
        console.log(combined[attribute]);
    }

}