Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
Dirk Boer Avatar asked Mar 27 '26 21:03

Dirk Boer


1 Answers

Try something like -

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

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

like image 196
Gupta.Swap Avatar answered Mar 29 '26 10:03

Gupta.Swap