【问题标题】:Merging two objects in JavaScript在 JavaScript 中合并两个对象
【发布时间】:2012-07-04 06:06:31
【问题描述】:

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

我有什么方法可以将这两个对象组合成一个具有两个子对象(关联数组)的对象?我想遍历它并每次获取一组属性?

谢谢

【问题讨论】:

  • JS中没有关联数组的概念,这些都是js对象
  • 你的意思是像var attributes = [{...},{...}];?我推荐阅读MDN JavaScript Guide,它应该能让你对JS基础有一个很好的了解。
  • 我认为@FelixKling 就在这里。这不完全是合并,OP 似乎在寻求一种将两个对象合并为 1 的方法,这很简单:[attributes1, attributes2] 甚至 ({library: attributes1, menu: attributes2})

标签: javascript associative-array


【解决方案1】:

是的,它们不是数组,但是您可以拥有对象数组,我认为您正在寻找的是:

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

【讨论】:

    【解决方案2】:

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

    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 k = [attributes, attributes1];
    • 是的,可以做到。我虽然如果他有两个以上的关联数组,那么在这种情况下,如果他想动态输入它们,那就太好了:)
    【解决方案3】:
    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]);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-30
      • 2013-01-17
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      相关资源
      最近更新 更多