Jaaaaaaay Jaaaaaaay - 1 month ago 5
Javascript Question

Improve performance when update objects in array with External Data input

I need to update specific objects in array. There is an external data input(array of objects)with the same key but different values. I need to update the old array with new array based on keys. Currently I use four for-loops to update the array. The performance is bad if oldData[] has 200+ items and newData[] has 100+ items. I'm wondering if there is any better way to do this.

I have below code as an example:

/* Object structure needs to stay the same*/
var oldData = [
{
"10001":{
name : 'Bill\'s Truck',
type : 'Truck',
speed: 50,
string: 'This is a huge string I also need to update'
}
},
{
"56781":{
name : 'Jay\'s Van',
type : 'Van',
speed: 60,
string: 'This is a huge string I also need to update'
}
}
];
$scope.oldData= oldData;

/*This data is actually from external API*/
var newData = [
{
"10001":{
name : 'Bill\'s Truck',
type : 'Truck',
speed: 80
}
}
];

/*Is there any better way to do this?*/
for(var old_index in oldData){
var old_device = oldData[old_index];
for(var old_deviceID in old_device){
for(var new_index in newData){
var new_device = newData[new_index];
for(var new_deviceID in new_device){
if(old_deviceID === new_deviceID){
console.log('Gotcha' + old_deviceID);
oldData[old_index] = angular.copy(new_device);
}
}
}
}
}


A working jsfiddle: http://jsfiddle.net/Lvc0u55v/11253/

Answer

You can improve it by using:

  1. Object.keys to simplify the inner loops.

  2. Access the needed property (given that you need to update speed only here) instead of looping through all the properties - you can do away with copying whole objects using angular.copy.

Demo below:

var oldData=[{10001:{name:"Bill's Truck",type:"Truck",speed:50,string:"This is a huge string I also need to update"}},{56781:{name:"Jay's Van",type:"Van",speed:60,string:"This is a huge string I also need to update"}}];
var newData=[{10001:{name:"Bill Dodge Ram",type:"Truck",speed:80}}];

oldData.forEach(function(element) {
  if (Object.keys(element)[0] === Object.keys(this[0])[0]) {
    element[Object.keys(element)[0]].speed = this[0][Object.keys(this[0])[0]].speed;
  }
}, newData);

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

Comments