2015-04-04 17 views
2

我有两个对象数组。 arrayOne包含的项目类型的myObject1什么是在JavaScript中部分复制对象数组的最优雅的方式

var myObject1 = { 
    Id: 1, //key 
    params: { weight: 52, price: 100 }, 
    name: "", 
    role: "" 
}; 

arrayTwo包含的myObject2项目类型:

var myObject2 = { 
     Id: 1, //key 
     name: "real name", 
     role: "real role" 
    }; 

我想从arrayTwo所有namesroles复制到arrayOneid是关键,两个数组都包含myObjects,并由'id`调整。

+0

什么'阵列one'和'阵列two'? – thefourtheye 2015-04-04 06:10:42

+0

你的意思是当id匹配时从arrayTwo复制名称和角色到arrayOne。 – 2015-04-04 06:11:32

+0

@DubemEnyekwe是 – sreginogemoh 2015-04-04 06:20:35

回答

1

在线性时间运行的溶液。

var arrayOne; \t // Array containing objects of type myObject1 
 
var arrayTwo; \t // Array containing objects of type myObject2 
 
var tempObj = {}; 
 

 
// Transform arrayOne to help achieve a better performing code 
 
arrayOne.forEach(function(obj){ 
 
\t tempObj[obj.id] = obj; 
 
}); 
 

 
// Runs on linear time O(arrayTwo.length) 
 
arrayTwo.forEach(function(obj){ 
 
\t // Note, since I'm not adding any thing to the arrayTwo 
 
\t // I can modify it in this scope 
 
\t var match = tempObj[obj.id]; 
 
\t 
 
\t if(match){ 
 
\t \t // If a match is found 
 
\t \t obj.name = match.name; 
 
\t \t obj.role = match.role; 
 
\t } 
 
});

+0

对'tempObj [obj.id] = obj;' - >'未获取TypeError:无法设置'undefined'的属性'4' – sreginogemoh 2015-04-04 08:10:37

+0

您错过了初始化'tempObj' =>'var tempObj = [];' – sreginogemoh 2015-04-04 08:12:48

+0

Doh !!!,@sreginogemoh感谢你的追捕。 – 2015-04-04 20:50:37

2

如果两个阵列被保证是全等,则与使用的jQuery.extend(),将码是微不足道:

$.each(arrayOne, function(i, obj) { 
    $.extend(obj, arrayTwo[i]); 
}); 
+0

只要2个数组保持一致,这将是一个合适的解决方案,否则,这里将需要不同的方法。 – 2015-04-04 07:12:41

+0

@YairNevet,错,是的。我的答案是否已经说过? – 2015-04-04 21:30:54

相关问题