简体   繁体   English

如何合并两个数组并使它们成为 JavaScript 中的对象数组

[英]How can I merge two arrays and make them array of objects in JavaScript

I have a simple question.我有一个简单的问题。 I have two arrays A and B, I want to return array of object with mixing the two arrays.我有两个数组 A 和 B,我想通过混合两个数组返回对象数组。

For example:例如:

let a = [ 1, 2 ]

let b = [ 3, 4 ]

Expected result :预期结果

const C = [
   { 
      a: 1,
      b: 3 
   },
   { 
      a: 2,
      b: 4 
   }
]

How can I do this?我怎样才能做到这一点?

I tried to forloop A then B and assign everytime but it didn't work.我试图 forloop A 然后 B 并每次都分配,但它没有用。

You can use array map method on one of the array and use index to retrieve the element from the second array您可以在数组之一上使用数组映射方法,并使用index从第二个数组中检索元素

 let a = [1, 2] let b = [3, 4]; let c = a.map((item, index) => { return { a: item, b: b[index] } }); console.log(c)

Something like this should work:这样的事情应该工作:

 let a = [1, 2]; let b = [3, 4]; // From @brk. This transforms each element of a to an object containing a's value and b's value let c = a.map((item, index) => { a: item, b: b[index] }); // Another way. Iterates through each element for (let i = 0; i < a.length; i++) { c[i].a = a[i]; c[i].b = b[i]; } // Yet another. A combination of the first two. for (let [index, item] of Object.entries(a)) { c[index] = { a: item, b: b[index] }; }

There's certainly a more elegant solution, but it evades me at the moment肯定有更优雅的解决方案,但目前它避开了我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript:如何合并这两个不完整对象的 arrays 并制作完整对象的数组 - JavaScript: how can I merge these two arrays of incomplete objects and make an array of complete objects 如何在JavaScript中合并两个对象数组 - How can I merge two arrays of objects in JavaScript 如何在Javascript中创建自定义对象数组的数组? - How can I make an array of arrays of custom objects in Javascript? 如何通过使用键,值对将具有两个不同大小的两个对象数组合并到一个数组中? - How can I merge two array of objects with two different sizes by using key, value pair to merge them into one array? 如何按键合并两个对象数组并将合并的数据放在子数组中 - How can I Merge two Arrays of Objects by Key & Place the Merged data in a Sub Array 当一个数组是二维的时,如何将两个 arrays 对象合并在一起? - How can I merge two arrays of objects together when one array is 2D? 如何按键合并两个对象中的 arrays (Javascript) - How to merge the arrays in two objects by key (Javascript) 如何合并javascript中的两个arrays对象? - how to merge two arrays of objects in javascript? 如何在Javascript中将对象数组合并为JSON数组 - How to merge arrays of objects into a JSON array in Javascript 如何合并两个数组以在JavaScript中创建一个数组? - How do I merge two arrays to create one array in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM