Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  171] [ 6]  / answers: 1 / hits: 79978  / 11 Years ago, sat, may 4, 2013, 12:00:00

I have several Javascript prototypes. Initially, instances will have only ID's filled in, with some generic place holder information for other data. I then send a message to the server with the ID and the object type (using jQuery's AJAX function) and the server returns a JSON object with all the missing information (but no ID). The variables in the returned object have the exact same name as those in the existing object.



What's the easiest way to transfer this into the existing empty object? I've come up with a few alternatives




  • set the object equal to the returned object, then copy in the id (loses prototype functions?)

  • create a function for each object that takes an object with identical structure and copies the data

  • loop through the key-value pairs of the JSON object to and copy them to existing object



If I use the third option, is this the correct way to do that? :



for (var key in json) {
if (object.hasOwnProperty(key)) {
object[key] = json[key];
}
}


assuming json is the returned object and object is the existing object.


More From » jquery

 Answers
36

Try this using extend():



var newObject = jQuery.extend({}, oldObject);

[#78432] Friday, May 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinityr

Total Points: 49
Total Questions: 107
Total Answers: 96

Location: Mayotte
Member since Fri, Oct 1, 2021
3 Years ago
;