-1

Assuming I have an array of arrays e.g.

let data = [ ['a', 'b', 'c'], [1,2,3], ['@', '!' , '%'] ]

How can I convert this into an array of objects such that the first element of each array gets put into an object, the second element gets put into another object, etc. For example the desired output for the 2d array above would be this:

     [ {charatcer: 'a', number: 1, symbol: '@'}, 
       {charatcer: 'b', number: 2, symbol: '!'}, 
       {charatcer:'c', number: 3, symbol: '%'}   ];
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Courtney White
  • 612
  • 8
  • 22

2 Answers2

2

You could zip the arrays together using .map() to produce the following transformed array:

[
  ["a", 1, "@"], ["b", 2, "!"], ["c", 3, "%"]
]

and then again use .map() on the zipped 2d array to create an object from each array using destructuring and shorthand property names like so:

let data = [['a', 'b', 'c'], [1,2,3], ['@', '!' , '%']];

const zipped = data[0].map((_, i) => data.map(arr => arr[i]));
const res = zipped.map(([character, number, symbol]) => ({character, number, symbol}));
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
-1

const data = [ ['a', 'b', 'c'], [1, 2, 3], ['@', '!' , '%'] ];
const comb = r => r[0].map((_, i) => ({character: r[0][i], number: r[1][i], symbol: r[2][i]}));
console.log(comb(data));
pank
  • 132
  • 1
  • 3