Wednesday 15 May 2013

javascript - deep merge objects with AngularJS -


Normally for the shallow copy objects I angular.extend () < Here is an example:

  var object1 = {"key": "abc123def456", "message": {"subject": "is a question", "to": " Example1@example.com "," to ":" example2@example.com "}}; Var object2 = {"key": "00700916391"}; Console.log (angular extension ({}, object1, object2));   

We must give:

  {"key": "00700916391", "message": {"subject": "is a question", " "From:" example1@example.com "," to ":" example2@example.com "}}   

But if I want to merge the object then the parent key is over Written by Kid Objects:

  var object1 = {"key": "abc123def456", "message": {"subject": "is a question", "to": " Example1@example.com, "" to ":" example2@example.com "}}; Var object2 = {"key": "00700916391", // Overwrite "message" to me: {// Do not overwrite me! "Subject": "What's happening?", // Overwrite me on "something": "Add something" // add me}}; Console.log (Merge (object1, object2));   

We have to give:

  {"key": "00700916391", "message": {"subject": "What is happening? "," From ":" example1@example.com "," to ":" example2@example.com "," something ":" something new "}}   
  • Is there an angular function that already merges a deep, which I do not know?

  • Use

    angular 1.4 or later

    Usage:

    < Unlike extension () , merge () returns a deep copy in the object properties of the recurring source object.
      Angular Merge (object 1, object 2); Merge object 1 in object 1   

    Older version of the corner:

    Let's say no ordinary recursive algorithm should be That they are both results of JSON.stringify or similar:

      function merge (obj1, obj2) {// our merge function var result = {}; // for each property in obj1 (obj1 in var i) {// in obj1 (obj2 in i) & amp; amp;; (obj1 [i] type === "object") & amp; amp; ; (I! == faucet)) {Results [i] = Merge (obj1 [i], obj2 [i]); // if it is an object, then merge} and {result [i] = obj1 [i]; // add it to the result}} for (i in obj2) {// add other properties of the object if (i in the result) {// the conflict continues; } Results [i] = obj2 [i]; } Return results; }   

    (note, arrays are not handled here)

No comments:

Post a Comment