Search code examples
javascriptlodash

How to use lodash's merge with a custom timestamp property


I am trying to merge two objects together and I want the property that has the higher of the two timestamps to be the one that wins. Is this possible or should I be using a different function? Please note, this object holds user preferences and can contains an unlimited number of properties.

Here is what I am trying to merge with the desired outcome.

let preferences1 = {
  'favorite-color': {
    timestamp: 1,
    data: 'red'
  },
  'nickname': {
    timestamp: 1,
    data: 'dude'
  }
};

let preferences2 = {
  'favorite-color': {
    timestamp: 2,
    data: 'black'
  }
};

let outcome = {
  'favorite-color': {
    timestamp: 2,
    data: 'black'
  },
  'nickname': {
    timestamp: 1,
    data: 'dude'
  }
};

const result = merge({}, preferences1, preferences2);

Solution

  • If you are using lodash 4+, it looks like the mergeWith function would be helpful here.

    let preferences1 = {
      'favorite-color': {
        timestamp: 1,
        data: 'red'
      },
      'nickname': {
        timestamp: 1,
        data: 'dude'
      }
    };
    
    let preferences2 = {
      'favorite-color': {
        timestamp: 2,
        data: 'black'
      }
    };
    
    let outcome = _.mergeWith({}, preferences1, preferences2, function (obj, src) {
      if (!obj || !obj.timestamp || !src.timestamp) return undefined;
      if (obj.timestamp > src.timestamp) return obj;
      return src;
    });