Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two object literals in javascript

Tags:

javascript

I have two object literals:

var animal = {
    eat: function() {
        console.log("eating...");
    }
}

var dog = {
    eat: "this has to be replaced when merged",
    nrOfLegs: 4
}

Need a merging function like this:

dog = someMergingFunction(animal, dog);

That produces:

{
    eat: function() {
        console.log("eating...");
    },
    nrOfLegs: 4
}

One of the object literals has to replace identical properties.

How do I do this in Javascript?

like image 216
ajsie Avatar asked Dec 01 '10 02:12

ajsie


1 Answers

What about spread syntax ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

var obj1 = { foo: 'bar', x: 42 };

var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 } 
like image 64
Ja Loc Avatar answered Oct 18 '22 03:10

Ja Loc