0

When assigning objects in javascript how do we determine the properties already existing in the assigned object is not being replaced. For example say:

var foo = {
   property1: "a",
   property3: "d"
}

var bar = {
   property1 : "b",
   property2 : "c"
}

then

a = b

would replace property1 in foo with b. In the context I'm considering, we are not sure whether the property1 of foo is existing when the assignment happens. So when assigning the option is to check if property1 exists, if not only then assign the property1 from b. So simple a=b assignment is not an option. So is there a way to assign an object which will only append the properties which are not existing in the object assigned to, while not replacing the already existing ones.

I guess one way to do it would be to :

for(var prop in b){
   if(!(a[prop])){
      a[prop] = b[prop]; 
   }
}

Is there a better shorthand way?

2
  • Sorry, can't understand you - a and b are undefined in your example. Did you mean foo = bar? Commented Aug 9, 2014 at 8:02
  • @Amadan - That is absolutely true. Anyway my comment doesn't seem to do what Phabtar is trying to do so please ignore it. Commented Aug 9, 2014 at 8:06

1 Answer 1

1

It sounds like you want something like jQuery.extend: http://api.jquery.com/jquery.extend/.

But assuming you don't want to use jQuery, here is a native JS implementation example that supports nested (deep) objects as well (http://jsfiddle.net/DqgYQ/):

function extend(target, src, deep){
    if(typeof target !== 'object' || typeof target === 'undefined' || target === null) return target;

    for(var prop in src){
        var value = target[prop];
        var copy = src[prop];

        if(deep && typeof copy === 'object'){
            value = typeof value === 'undefined' ? {} : value;

            target[prop] = extend(value, copy, deep);
        }
        else{
            target[prop] = copy;
        }
    }

    return target;
};

See the fiddle for a working example.

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

2 Comments

Thanks, but I'm looking for a better solution without Jquery.
My solution isn't jQuery. It's native JS.

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.