-3

I have two arrays like this:

const opciones = ['A', 'B', 'C', 'D'];
const valoracion = [true, false, false, false];

And the, I want to create a new Array of Objects from these two arrays, like this:

const respuestas = [
  {opc: 'A', val: true},
  {opc: 'B', val: false},
  {opc: 'C', val: false},
  {opc: 'D', val: false},
]
Tabi
  • 109
  • 2
  • 6
  • 1
    a simple `for` loop can do that, you can find easy tutorials of this on google and much probably many other already answered questions here in SO. Please, read [ask] and if you tried something and didn't achieve your goal, then return with a specific question – Calvin Nunes Dec 18 '19 at 16:52

3 Answers3

1

This is commonly called a "Zip" operation for obvious reasons, and is quite easy to do using map in javascript.

const opciones = ['A', 'B', 'C', 'D'];
const valoracion = [true, false, false, false];

var result = opciones.map( (v,i) => ({opc:v, val:valoracion[i]}));
console.log(result);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You can use map function and transform first array into array of objects:

const result = opciones.map((item, index) => ({
  opc: item,
  val: valoracion[index]
}));
demkovych
  • 7,827
  • 3
  • 19
  • 25
0

You could take a dynamic approach with an object with the wanted keys and values and reduce the object's entries.

const
    opc = ['A', 'B', 'C', 'D'],
    val = [true, false, false, false],
    result = Object
        .entries({ opc, val })
        .reduce((r, [k, a]) => a.map((v, i) => Object.assign(r[i] || {}, { [k]: v })), []);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392