Dirk Boer
Dirk Boer

Reputation: 9075

jQuery $.extend without overriding target properties

Is it possible to extend an object without overriding the properties that are already set? In the following example I'm looking for a way to add 2 wings to the cat, but keepings it's 4 legs.

var cat  = { legs: 4 };
var bird = { legs: 2, wings: 2 }

// some references in my application to the original cat
var some_cat = cat;

$.extend( cat, bird );

// expected { legs: 4, wings: 2 }
console.log( some_cat );

Update

I forgot to make it clear in the original question / example, but it is important that it modifies the original cat object.

Upvotes: 3

Views: 1564

Answers (1)

Gupta.Swap
Gupta.Swap

Reputation: 265

Try something like -

for (prop in bird) {
    if(!cat.hasOwnProperty(prop)) {
        cat[prop] = bird[prop];
    }
}

After cat = {legs: 4, wings: 2}

Upvotes: 4

Related Questions