Skip to content Skip to sidebar Skip to footer

How Can I Make An Array Of Objects From N Properties Of N Arrays In Js?

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

Solution 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);

Solution 2:

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

const result = opciones.map((item, index) => ({
  opc: item,
  val: valoracion[index]
}));

Solution 3:

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);

Post a Comment for "How Can I Make An Array Of Objects From N Properties Of N Arrays In Js?"