Home > database >  How to Loop a Nested array by the Inside Array in dynamic solution
How to Loop a Nested array by the Inside Array in dynamic solution

Time:12-03

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 ammount =  price * qty;
    ordersObj.push({name,price,qty,ammount})
 }

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

CodePudding user response:

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 ammount =  price * qty;
    ordersObj.push({name,price,qty,ammount})
 }

CodePudding user response:

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' ]
]
*/
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related