Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
How to Loop a Nested array by the Inside Array in dynamic solution

I am having problems with my code because I think it is not flexible if a new array is inserted in my nested array I will not consider the new array. The important thing is how do I access to the first element, then second and so on at the same time of each array.

Here is an Example:

    const nestedArr = [
    [
            "COCA - COLA ORIGINAL 355 ML VIDRIO RET",
            "COCA - COLA ORIGINAL 600 ML PET NR",
            "COCA - COLA ORIGINAL 2.5 LT RET"],
        [
            "$176.02",
            "$100.00",
            "$130.00"
        ],
        [
            "10",
            "3",
            "15"
        ]
    ]

const ordersObj = []

for (let i=0; i< nestedArr[0].length; i++){
    var name = orderArr[0][i];
    var price = Number(orderArr[1][i].replace("$",""));
    var qty = orderArr[2][i];
    var amount =  price * qty;
    ordersObj.push({name,price,qty,amount})
 }

What I would like to do is to avoid to put 0,1,2 to set the position of which nested array I want to access, I want to run a loop or change my code so that 0,1,2 are not hard coded.

Regards

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Seems like your code is a bit messy I guess:

const nestedArr = [
    [
            "COCA - COLA ORIGINAL 355 ML VIDRIO RET",
            "COCA - COLA ORIGINAL 600 ML PET NR",
            "COCA - COLA ORIGINAL 2.5 LT RET"],
        [
            "$176.02",
            "$100.00",
            "$130.00"
        ],
        [
            "10",
            "3",
            "15"
        ]
    ]

const ordersObj = []

for (let i=0; i< nestedArr[0].length; i++){
    // This has no value yet
    // var name = orderArr[0][i];
    // this should be
    var name = nestedArr[0][i]
    var price = Number(nestedArr[1][i].replace("$",""));
    var qty = nestedArr[2][i];
    var amount =  price * qty;
    ordersObj.push({name,price,qty,amount})
 }
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would recommend not trying to do it all in one loop, but rather define a constructor function for you object, and map the source nestedArr to a more usable 2D array with each property at their given index in the sub-arrays (here using a utility zip function, see this question for discussion).

const nestedArr = [
  ['COCA - COLA ORIGINAL 355 ML VIDRIO RET', 'COCA - COLA ORIGINAL 600 ML PET NR', 'COCA - COLA ORIGINAL 2.5 LT RET'],
  ['$176.02', '$100.00', '$130.00'],
  ['10', '3', '15'],
];

const OrderObj = ([name, price, qty]) => {
  const _price = Number(price.replace('$', ''));
  const _qty = Number(qty);

  return {
    name,
    price: _price,
    qty: _qty,
    amount: _price * _qty,
  };
};

const zip = (...rows) => [...rows[0]].map((_, i) => rows.map((row) => row[i]));

const orderObjs = zip(...nestedArr).map(OrderObj);

console.log(orderObjs);

// console.log(zip(...nestedArr));
/*
[
  [ 'COCA - COLA ORIGINAL 355 ML VIDRIO RET', '$176.02', '10' ],
  [ 'COCA - COLA ORIGINAL 600 ML PET NR', '$100.00', '3' ],
  [ 'COCA - COLA ORIGINAL 2.5 LT RET', '$130.00', '15' ]
]
*/

Adding more rows to the nestedArr simply requires adjusting your constructor to account for the new rows with the destructured parameters serving as a legend for the rows in the nestedArr.

const nestedArr = [
  ['COCA - COLA ORIGINAL', 'COCA - COLA ORIGINAL', 'COCA - COLA ORIGINAL'],
  ['$176.02', '$100.00', '$130.00'],
  ['355 ML VIDRIO RET', '600 ML PET NR', '2.5 LT RET'], // <─── added row
  ['10', '3', '15'],
];

//                               ┌───────────────────────────── added index
const OrderObj = ([name, price, size, qty]) => {
  const _price = Number(price.replace('$', ''));
  const _qty = Number(qty);

  return {
    name,
    size, // <───────────────────────────────────────────────── added property
    price: _price,
    qty: _qty,
    amount: _price * _qty,
  };
};

const zip = (...rows) => [...rows[0]].map((_, i) => rows.map((row) => row[i]));

const orderObjs = zip(...nestedArr).map(OrderObj);

console.log(orderObjs);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda