Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 2 objects without duplicated content

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?

like image 763
K20GH Avatar asked Mar 08 '23 00:03

K20GH


1 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);
like image 82
KevBot Avatar answered Mar 20 '23 23:03

KevBot