1

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I just finished writing this same answer! +1 for beating me to it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.