merging local and server updates

Viewed 38

Need to merge 2 lists of updates, local and server.
Using redux (but it doesn't really matter) i need to refresh the updates list.

const localUpdates = [
  { id: 1, name: 'one', date: 'old' },
  { id: 2, name: 'two', date: 'old' },
  { id: 3, name: 'three', date: 'old' },
];

const serverUpdates = [
  { id: 1, name: 'one', date: 'new' },
  { id: 4, name: 'four', date: 'new' },
];

Desired output:

updates: [
  { id: 1, name: 'one', date: 'new' },
  { id: 2, name: 'two', date: 'old' },
  { id: 3, name: 'three', date: 'old' },
  { id: 4, name: 'four', date: 'new' },
]

Thanks in advance (having brainfreeze looiking at this for the past hour)

2 Answers

You can make use of Array.prototype.reduce followed by Object.values to the concated array in order to perform an update

const localUpdates = [
  { id: 1, name: 'one', date: 'old' },
  { id: 2, name: 'two', date: 'old' },
  { id: 3, name: 'three', date: 'old' },
];

const serverUpdates = [
  { id: 1, name: 'one', date: 'new' },
  { id: 4, name: 'four', date: 'new' },
];


const concatArr = localUpdates.concat(serverUpdates);
// we will be excepting new values for same id

const resObj = concatArr.reduce((acc, item)=> {
   acc[item.id] = {...(acc[item.id] || {}), ...item};
   return acc;
}, {})

console.log(Object.values(resObj));

create a temporary object, loop over both arrays and add each object's id in the temporay object as key and whole object as value. Objects with same id's will be overwritten. Finally use Object.values to get the merged objects in an array.

const localUpdates = [
  { id: 1, name: 'one', date: 'old' },
  { id: 2, name: 'two', date: 'old' },
  { id: 3, name: 'three', date: 'old' },
];

const serverUpdates = [
  { id: 1, name: 'one', date: 'new' },
  { id: 4, name: 'four', date: 'new' },
];

const obj = {};
localUpdates.forEach(local => (obj[local.id] = local));
serverUpdates.forEach(server => (obj[server.id] = server));


console.log(Object.values(obj));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related