[英]What is the most elegant way of partly copying object arrays in JavaScript
I have two arrays of objects. 我有两个对象数组。
arrayOne
contain items type of myObject1
: arrayOne
包含myObject1
项目类型:
var myObject1 = {
Id: 1, //key
params: { weight: 52, price: 100 },
name: "",
role: ""
};
arrayTwo
contained items type of myObject2
: arrayTwo
包含myObject2
项目类型:
var myObject2 = {
Id: 1, //key
name: "real name",
role: "real role"
};
I want to copy all names
and roles
from arrayTwo
to arrayOne
. 我想将所有
names
和roles
从arrayTwo
到arrayOne
。 id
is the key, both arrays contains myObjects
with that is mached by 'id`. id
是键,两个数组都包含myObjects
,并由'id`组成。
If the two arrays are guaranteed to be congruent, then with the use of jQuery.extend()
, the code is trivial : 如果保证两个数组是一致的,那么使用
jQuery.extend()
,代码就很简单了:
$.each(arrayOne, function(i, obj) {
$.extend(obj, arrayTwo[i]);
});
A solution that runs in linear time. 在线性时间内运行的解决方案。
var arrayOne; // Array containing objects of type myObject1 var arrayTwo; // Array containing objects of type myObject2 var tempObj = {}; // Transform arrayOne to help achieve a better performing code arrayOne.forEach(function(obj){ tempObj[obj.id] = obj; }); // Runs on linear time O(arrayTwo.length) arrayTwo.forEach(function(obj){ // Note, since I'm not adding any thing to the arrayTwo // I can modify it in this scope var match = tempObj[obj.id]; if(match){ // If a match is found obj.name = match.name; obj.role = match.role; } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.