-1

I'm wondering what is the best way of copying object property's from/to another object using AngularJS/JavaScript

Below is the Json object I'm getting:

{  
   "application":{  
      "number":"323-23-4231",
      "amount":"234.44",
      "ref_name":"Thomas Edison"
   },
   "borrower":{  
      "prefix":"Mr",
      "first_name":"Eric",
      "middle_name":"E",
      "last_name":"Schulz",
      "date_of_birth":"09/29/1975",
      "email_address":"myemail@HOTMAIL.COM",
      "phones":[  
         {  
            "number":"(555)555-5555",
            "type":"Mobile"
         }
      ]
   }
}

Using the above Json object I want the new JSON object data to be looks like this:

{  
   "number":"323-23-4231",
   "amount":"234.44",
   "ref_name":"Thomas Edison",
   "prefix":"Mr",
   "first_name":"Eric",
   "middle_name":"E",
   "last_name":"Schulz",
   "date_of_birth":"09/29/1975",
   "email_address":"myemail@HOTMAIL.COM",
   "phones":[  
      {  
         "number":"(555)555-5555",
         "type":"Mobile"
      }
   ]
}
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • http://stackoverflow.com/questions/9362716/how-to-duplicate-object-properties-in-another-object :D There are many ways... What have you tried yet? You just need a simple mapper right – PSL Oct 09 '14 at 00:23
  • I have tried without using any built-in methods like `newobj.number = oldobj.applicaiton.number` I'm looking to implement something using built-in methods/functions in AngularJS – Nick Kahn Oct 09 '14 at 00:31
  • i did not intend to have but it was copy/paste, ignore the hashkey – Nick Kahn Oct 09 '14 at 00:34

1 Answers1

1

If you have the original object in a variable called oldObj, you could do something like this (untested):

newObj = {}
newObj = angular.extend(newObj, oldObj.application)
newObj = angular.extend(newObj, oldObj.borrower)

There are lots of ways to copy the properties of one object to another in different frameworks. Angular has the built-in angular.extend which you can read about here

You could even do this without using any fancy methods:

newObj.number = oldObj.application.number
newObj.amount = oldObj.application.amount
newObj.ref_name = oldObj.application.ref_name
newObj.prefix = oldObj.borrower.prefix
...

But that'd be kinda silly :)

Nathan Manousos
  • 13,328
  • 2
  • 27
  • 37