1

I've 2 objects
var obj1 = {a: 1, b: true, c: false};
var boj2 = {b: true, c: true, d: 1};

I would like to have a union of two object like this:
{a: 1, b: true, c: false, d: 1};

I've tried with $.extend but it overwrites c and I obtain
{a: 1, b: true, c: true, d: 1};

Some suggestions?

davidinho
  • 169
  • 1
  • 14

3 Answers3

1

You can reverse the order

var obj1 = {a: 1, b: true, c: false}; 
var obj2 = {b: true, c: true, d: 1};
console.log($.extend(obj2,obj1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
1

I've put together a JSFiddle that may help solve your problem - see https://jsfiddle.net/fhjuL22s/1/

var obj1 = {a: 1, b: true, c: false, e: 0}; 
var obj2 = {b: true, c: true, d: 1, e: 1};

var result = {};

for (var prop in obj1){
    result[prop] = obj1[prop]
    ? (obj2.hasOwnProperty(prop) ? obj2[prop] : obj1[prop])
    : obj1[prop];
}

for (var prop in obj2) {
    if (!result.hasOwnProperty(prop))
    result[prop] = obj2[prop];
}

console.log(result)
combatc2
  • 1,215
  • 10
  • 10
0

Did you try googling it? The answer can be found here or here, depending on your wishes:

  1. Create a new object and merge both obj1 and boj2 into that. You will end up with a new object though, so do not use this when you need to modify the first object. Example can be found at link 1.
  2. Create your own method for this. Example can be found at link 2.
Niek Janssen
  • 56
  • 1
  • 8