Reputation: 53
I need to merge 2 objects in angularJS Im trying with angular.merge(obj1, obj2), but that's not what I expected
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 ? Thanks
Upvotes: 0
Views: 427
Reputation: 7066
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:
angular.forEach(obj1, function(obj) {
angular.merge(obj, obj2);
});
Upvotes: 0
Reputation: 253
Just do an iteration on first object
for(var i in obj1) {
angular.merge(obj1[i], obj2);
}
Upvotes: 1
Reputation: 48367
You can do it using native
javascript.
One of the solutions includes forEach
method in combination with Object.assign
in order to merge the properties.
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);
Upvotes: 1