1

For example say I've got the following object:

person = {firstname:"Freddy", lastname:"Fish", age:15}

In this object I would like to replace the first and lastname of the person.

Instead of using

person.firstname = "Earthworm";
person.lastname = "Jim";

I would like to use something like

person += {firstname:"Earthworm", lastname: "Jim"}
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
inControl
  • 2,215
  • 4
  • 24
  • 39
  • possibly you need see about [jQuery.extend](http://api.jquery.com/jquery.extend/) – Grundy Mar 05 '14 at 10:45
  • @Stijn: I’m not sure it is a duplicate. That question asked about merging (which kind of implies that the two objects might not have properties with the same name), whereas this question is asking about replacing property values (which implies the objects have identical property names). – Paul D. Waite Mar 05 '14 at 10:49
  • 1
    @PaulD.Waite The specific example in that question does not ask to replace a value indeed, but the answers seem to cover adding properties and replacing properties. – user247702 Mar 05 '14 at 10:50
  • Not exactly the same question, but the answers from here can also help you: [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – user247702 Mar 05 '14 at 11:03

3 Answers3

2

If you don't mind to use jQuery for that purpose you can do this:

$.extend(person ,{firstname:"Worm", lastname: "Jim"});

It will replace the values for the existing fields and add the new ones -> $.extend()

Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
2

Some JavaScript libraries include a method called extend, which does what you want:

You can see Underscore’s implementation here, in case you don’t want to use a library:

And now you can see it here too, no click necessary:

_.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
        if (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
1

You can use Object.defineProperty()

http://jsfiddle.net/9Bfrc/1/

person1 = {firstname:"Freddy", lastname:"Fish", age:15};
person2 = {firstname:"errr", lastname:"Fsdfish"};
props=Object.getOwnPropertyNames(person2);
for(i in props){
    var prop=''+props[i];
    Object.defineProperty(person1,prop,{value:person2[prop]});
}
console.log(person1); //Object { firstname="errr", lastname="Fsdfish", age=15}