[英]Improve performance when update objects in array with External Data input
我需要更新數組中的特定對象。 有一個具有相同鍵但值不同的外部數據輸入(對象數組)。 我需要使用基於鍵的新數組更新舊數組。 目前,我使用四個for循環來更新數組。 如果oldData []有200多個項目,而newData []有100+多個項目,則性能會很差。 我想知道是否有更好的方法可以做到這一點。
我以下面的代碼為例:
/* 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);
}
}
}
}
}
可行的jsfiddle: http : //jsfiddle.net/Lvc0u55v/11253/
您可以使用以下方法進行改進:
Object.keys
簡化內部循環。
訪問所需的屬性(假設只需要在此處更新speed
),而不是遍歷所有屬性-您可以使用angular.copy
整個對象。
下面的演示:
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;}
您可以使用angular.merge(oldData, newData)
內置的angular方法來合並對象,如Angularjs文檔中對angular.merge
。 此外,還有angular.extends
,它僅合並對象的第一級而不會像angular.merge
那樣遞歸深入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.