Search code examples
javascriptarraysmergejavascript-objectsarray-difference

Javascript arrays and objects: Get differences and merge them


So I have this scenario where I have a client-app which sends data (array of objects) to a server which then forwards the data to other clients connected to this server.

In the client-app, the data is constantly changing, meaning: Values change, new objects inside the array pop up, objects being removed, and so on ...

Now I want the other clients to always receive the latest data. And because I dont want the client-app to just push the whole new data to the server which then forwards the whole new data to the other clients, I decided to let the client-app only push the changes (using this library: https://www.npmjs.com/package/deep-object-diff).

The other clients then receive an array of objects with only the data that has actually changed and because they know the previous data array, I want them to "merge" the array of changes with the old data object.

My actual problem is the merging. I dont know how to properly do this. Especially if I have an array of objects without any key for the objects.

So my data looks something like this:

let data = [
  {
    name: 'Peter',
    age: 26,
    sID: 546589995544
  },
  {
    name: 'John',
    age: 33,
    sID: 554589525469
  }
];

Actually there's much more but well, thats the structure.

So if the diff library says, this are the changes:

let changes = {
  {
    age: 34,
    sID: 554589525469
  }
};

(notice that I now have an object of objects, not an array of objects. Thats what the diff-library returns)

I want the merged object to be

[
  {
    name: 'Peter',
    age: 26,
    sID: 546589995544
  },
  {
    name: 'John',
    age: 34,
    sID: 554589525469
  }
];

(John is now one year older)

So I totally believe that this would be much easier if I had a key to the objects as an identifier, but still I think there has to be a solution for exactly this scenario. And as you can see, the sID property could act as an identifier, its just not a key.

I would apprectiate if someone could point out how to do it in both cases (with and without a specific key for the objects)


Solution

  • You can use .find() to find the object within the array where values should be changed, Object.assign() to set the values

    let data = [{
        name: 'Peter',
        age: 26,
        sID: 546589995544
      },
      {
        name: 'John',
        age: 33,
        sID: 554589525469
      }
    ];
    
    let changes = [{
      age: 34,
      sID: 554589525469
    }];
    
    for (let prop of changes) {
      let {sID} = prop;
      Object.assign(data.find(({sID: id}) => id === sID), prop)
    }
    
    console.log(data);