繁体   English   中英

在JavaScript中部分复制对象数组的最优雅方法是什么

[英]What is the most elegant way of partly copying object arrays in JavaScript

我有两个对象数组。 arrayOne包含myObject1项目类型:

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"
    };

我想将所有namesrolesarrayTwoarrayOne id是键,两个数组都包含myObjects ,并由'id`组成。

如果保证两个数组是一致的,那么使用jQuery.extend() ,代码就很简单了:

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

在线性时间内运行的解决方案。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM