Merge 2 objects without duplicated content

Viewed 5194

I'm trying to merge 2 objects together, however there is a possibility for X number of duplicated items. As an example, I already have historyExisting, and I want to add historyNew to it. You can see there are duplicates

Sample Data

var historyExisting =  { 
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956
}

var historyNew = { 
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
    }

Desired Outcome

var history = {
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
}

As you can see, the outcome is still kept in timestamp order, but any duplication has been removed. I've been trying to get the last item key/value in historyExisting, find that in historyNew, remove any items before that and then merge them but it seems extremely clunky.

This is server side in Node, so not browser dependent.

Any suggestions?

2 Answers

Using Object.assign:

(Supported in Node.js 4 and up)

var historyExisting = {
  '1505845390000': 295426,
  '1505757979000': 4115911,
  '1505677767000': 4033384,
  '1505675472000': 4033384,
  '1505591090000': 3943956
}

var historyNew = {
  '1505675472000': 4033384,
  '1505591090000': 3943956,
  '1505502071000': 3848963,
  '1505499910000': 3848963,
  '1505499894000': 3848963
}

var merged = Object.assign({}, historyExisting, historyNew);

console.log(merged);

Other options:

If you need to support a browser (or environment) that does not support Object.assign, you may have a tool available already in your arsenal such as jQuery's extend, or lodash's extend and many other polyfills. if you don't have access to such a tool, you can always write your own:

function extend(base, ...objs) {
  objs.forEach(obj => {
    Object.keys(obj).forEach(key => {
      base[key] = obj[key];
    })
  });
  return base;
}

var historyExisting = {
  '1505845390000': 295426,
  '1505757979000': 4115911,
  '1505677767000': 4033384,
  '1505675472000': 4033384,
  '1505591090000': 3943956
}

var historyNew = {
  '1505675472000': 4033384,
  '1505591090000': 3943956,
  '1505502071000': 3848963,
  '1505499910000': 3848963,
  '1505499894000': 3848963
}

var merged = extend({}, historyExisting, historyNew);

console.log(merged);

Using spread properties:

const history = {...historyExisting, ...historyNew};

which is pretty much identical to `Object.assign({}, You'll have to transpile to get this to work in node or almost any browser.

Related