0

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

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

Just do an iteration on first object

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

1 Comment

Perfect !! Thank you Keming
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.