mgs
mgs

Reputation: 5176

Copy Javascript Object into another Object, not creating new Properties

Suppose there are two objects

source = {
   name: "A",
   address: {
      city: "B",
      zipcode: "C"
   },
   car: {
      make: "D",
      model: "E"      
   }
};

target = {
   name: "",
   address: {
      city: ""
   }
};

Now I want to copy all data from source over to target. However, copying must only take place, if the corresponding property already exists in the target. It is something like jQuery's extend, without adding new properties. With the above data the result will be...

target = {
   name: "A",
   address: {
      city: "B"
   }
};

How can this be achieved easily?

Upvotes: 1

Views: 692

Answers (2)

Bergi
Bergi

Reputation: 664307

This should do it:

function extend(target, source) {
    for (var prop in source)
        if (prop in target) // <== test this
            if (typeof target[prop] === "object")
                extend(target[prop], source[prop]);
            else
                target[prop] = source[prop];
}

Disclaimer: This simple one does not work for arrays, enumerable prototype properties, null values…

You might as well change the outermost loop to

    for (var prop in target)
        if (prop in source)

depending on which of the two objects has less properties to enumerate.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227200

You could just loop through target and then grab the values from `source. I'd suggest a recursive function, since your object may have multiple sub-objects.

function fill_in_values(target, source){
    for(var prop in target){
        if(typeof target[prop] === 'object'){
            fill_in_values(target[prop], source[prop]);
        }
        else{
            target[prop] = source[prop];
        }
    }
}

Upvotes: 1

Related Questions