在 JavaScript 中合并两个对象

Merging two objects in JavaScript

本文关键字:两个 对象 JavaScript 合并      更新时间:2023-09-26

我有两个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"       
};

我有什么办法将两个对象组合成一个具有两个子对象(关联数组)的对象?我想循环它并每次获得一组属性?

谢谢

是的,那些不是数组,但你可以有对象数组,我认为你正在寻找的是这个:

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

是的,你可以很容易地做到这一点:-

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/

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