I am faced with a situation where I have a collection of objects, each containing multiple key-value pairs.
There will be numerous instances where various API calls or server-sent events (via websockets) will provide updated data for some objects in the collection. The challenge lies in the fact that each call only returns specific parts of the data for each object, rather than the entire set of information.
The main question here is how to efficiently update only the modified bits, considering that this data is utilized in a React application and we need to take into account immutability implications as well.
My initial approach involves matching the id
from the original data with the new data, followed by looping through the incoming data to identify the keys and updating the original data accordingly. However, there might be a more effective method to achieve this.
let original_data = [{
id: 1,
value_1: 'will only change when value_1 method is called for id=1',
value_2: 'will only change when value_2 method is called',
},
{
id: 2,
value_1: 'will only change when value_1 method is called for id=2',
value_2: 'will only change when value_2 method is called',
},
]
let replacement_data = [{
id: 1,
value_1: 'assume value_1 method was called for id=1',
}]
for (let i in replacement_data) {
//get the index matched by id
index = original_data.findIndex((x => x.id === replacement_data[i].id))
//replace only the data that has changed
for (var key in replacement_data[i]) {
original_data[index][key] = replacement_data[i][key]
}
}
console.log(original_data);
Although the current method works, I am concerned about its performance if faced with an event where thousands of such changes occur. Are there any potential optimizations or best practices that could improve this process?