简体   繁体   English

使用AngularJS合并两个对象

[英]Merge two objects with AngularJS

I need to merge 2 objects in angularJS Im trying with angular.merge(obj1, obj2), but that's not what I expected 我需要在angularJS中合并2个对象我正在尝试使用angular.merge(obj1,obj2),但这不是我期望的

First object 第一个对象

 // obj1
{
  "0": {
    "name": "340.jpg",
    "bytes": 21955,
    "link": "340.jpg?dl=0",
    "icon": "page_white_picture.png"
  },

  "1": {
    "name": "341.pdf",
    "bytes": 3394,
    "link": "340.pdf?dl=0",
    "icon": "page_white_acrobat.png"

  }

Second Object 第二个对象

// obj2
{
  "id_pro": "70",
  "nuevo": "true",
  "fecha_ser": "2017-10-18"
}

Expected result 预期结果

// Merged
{

  "0": {
    "name": "340.jpg",
    "bytes": 21955,
    "link": "340.jpg?dl=0",
    "icon": "icons64/page_white_picture.png",

    "id_pro": "70",
    "nuevo": "true",
    "fecha_ser": "2017-10-18"
  },

  "1": {
    "name": "341.pdf",
    "bytes": 3394,
    "link": "340.pdf?dl=0",
    "icon": "page_white_acrobat.png",

    "id_pro": "70",
    "nuevo": "true",
    "fecha_ser": "2017-10-18"

  }

}

Add the second object exactly in each group of first object. 将第二个对象完全添加到每个第一个对象组中。

Is possible with angular.merge or i need a own function ? 是否可以与angular.merge或我需要自己的功能? Thanks 谢谢

You can do it using native javascript. 您可以使用native javascript来实现。

One of the solutions includes forEach method in combination with Object.assign in order to merge the properties. 解决方案之一是将forEach方法与Object.assign结合使用,以合并属性。

 let obj={ "0": { "name": "340.jpg", "bytes": 21955, "link": "340.jpg?dl=0", "icon": "page_white_picture.png" }, "1": { "name": "341.pdf", "bytes": 3394, "link": "340.pdf?dl=0", "icon": "page_white_acrobat.png" } }; let second={ "id_pro": "70", "nuevo": "true", "fecha_ser": "2017-10-18" } Object.keys(obj).forEach(function(key){ Object.assign(obj[key],second); }); console.log(obj); 

Just do an iteration on first object 只需对第一个对象进行迭代

for(var i in obj1) {
    angular.merge(obj1[i], obj2);
}

It's worth noting that there are many ways to iterate the object. 值得注意的是,有很多方法可以迭代对象。 Since you're working with AngularJS anyway, you can use the Angular helper method: 由于无论如何都使用AngularJS,因此可以使用Angular helper方法:

angular.forEach(obj1, function(obj) {
    angular.merge(obj, obj2);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM