Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda