inControl
inControl

Reputation: 2314

How can I replace multiple object values with the values from another object?

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"}

Upvotes: 1

Views: 604

Answers (3)

user2587132
user2587132

Reputation:

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}

Upvotes: 1

Paul D. Waite
Paul D. Waite

Reputation: 98786

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

Upvotes: 2

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4501

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

Upvotes: 2

Related Questions