我需要更新数组中的特定对象。有一个外部数据输入(对象数组)具有相同的键但不同的值。我需要用基于键的新数组更新旧数组。目前我使用四个 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 来避免复制整个对象。复制
。
下面的演示:
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;}
关于javascript - 使用外部数据输入更新数组中的对象时提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266390/