从一个对象添加属性到另一个对象

时间:2013-10-16 11:27:26

标签: javascript underscore.js

我有两个具有相似结构的对象 -

    var locations = { 
        "regions": [{
        "name": "Asia Pacific",
        "handle": "asia-pacific",
        "iso_code": "",
        "iso_code_3": "",
        "countries": [{
            "name": "Republic of Korea",
            "iso_code": "kr",
            "iso_code_3": "kor"
          },{
            "name": "Japan",
            "iso_code": "jp",
            "iso_code_3": "jap"
          }
        ]
      }]
    }


    var additionalLocations = { 
        "regions": [{
        "name": "Asia Pacific",
        "handle": "asia-pacific",
        "iso_code": "",
        "iso_code_3": "",
        "countries": [{
            "name": "Malaysia",
            "iso_code": "my",
            "iso_code_3": "mys",
          }
        ]
      }]
    }

我怎样才能将国家,马来西亚从additionalLocations对象转移到location对象?

看起来应该是这样的 -

   var locations = { 
        "regions": [{
        "name": "Asia Pacific",
        "handle": "asia-pacific",
        "iso_code": "",
        "iso_code_3": "",
        "countries": [{
            "name": "Republic of Korea",
            "iso_code": "kr",
            "iso_code_3": "kor"
          },{
            "name": "Japan",
            "iso_code": "jp",
            "iso_code_3": "jap"
          },{
            "name": "Malaysia",
            "iso_code": "my",
            "iso_code_3": "mys",
          }
        ]
      }]
    }

我希望有一个漂亮的下划线方法可以帮我。

1 个答案:

答案 0 :(得分:0)

locations.regions[0].countries.push(additionalLocations.regions[0].countries[0])

如果你想在一个循环中为多个位置做这个,你需要多一点,但对于你发布的情况,这应该有效。