简体   繁体   中英

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.

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.

You can use array map method on one of the array and use index to retrieve the element from the second array

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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