-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
  • 99
  • 2
  • 3
  • 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
  • 128,537
  • 12
  • 134
  • 188
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
  • 5,854
  • 3
  • 16
  • 24
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
  • 351,820
  • 24
  • 303
  • 358