简体   繁体   English

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

[英]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 . 我想将所有namesrolesarrayTwoarrayOne 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.

相关问题 使用 Javascript arrays 计算集差的最快或最优雅的方法是什么? - What is the fastest or most elegant way to compute a set difference using Javascript arrays? 在 JavaScript 中不可变地从 object 中删除一组属性的最优雅方法是什么? - What is the most elegant way to remove an array of properties from an object immutably in JavaScript? 仅保存Javascript对象原始属性的最优雅方法 - Most elegant way to save only primitive properties of a Javascript object 使用Javascript / jQuery,将列表呈现到表格中的最优雅的方法是什么? - Using Javascript / jQuery, what is the most elegant way to render a list into a table? 在 JavaScript 构造函数中接受和处理不同选项的最优雅的方式是什么? - What is the most elegant way to accept and handle different options in JavaScript constructor? 什么是javascript中将字节转换为可读格式的最优雅方式 - What is the most elegant way in javascript to convert bytes into a readable format 最优雅的方式来创建一个JSON对象 - Most elegant way to create a JSON Object 插入此条件语句的最优雅方式是什么? - What is the most elegant way to insert this conditional statement? 创建 javascript 弹出窗口的最优雅方式? - most elegant way to create a javascript popup? 在 Javascript 中应用多个改变相同数组的函数的最优雅方法是什么? - What is the most elegant way to apply multiple functions that mutates the same array in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM