Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously.

Here's an example:

    const nestedArr = [
    [
            "ITEM A",
            "ITEM B",
            "ITEM C"
        ],
        [
            "$50.00",
            "$30.00",
            "$20.00"
        ],
        [
            "5",
            "2",
            "7"
        ]
    ]

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

I want to avoid manually specifying positions (0, 1, 2) to access different nested arrays and instead run a loop or modify the code to achieve this dynamically.

Best Regards

Answer №1

I would suggest avoiding trying to handle everything in a single loop. Instead, create a constructor function for your object and transform the source nestedArr into a more manageable 2D array where each property is located at its designated index within the sub-arrays. This can be achieved using a utility zip function (refer to this question for further 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' ]
]
*/

When adding additional rows to the nestedArr, you simply need to update your constructor to accommodate the new rows by utilizing destructured parameters as a guide 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);

Answer №2

Looks like the code could use some organizing:

const productArr = [
    [
            "APPLE - MACBOOK AIR",
            "APPLE - IMAC 27 INCH",
            "APPLE - IPHONE 13 PRO MAX"],
        [
            "$999.99",
            "$1799.00",
            "$1399.00"
        ],
        [
            "5",
            "2",
            "10"
        ]
    ]

const productsObj = []

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ending the jQuery Modal box

Struggling to create a simple modal on my own, and I'm facing some difficulties (probably because I'm more of an expert in jQuery - but let's not dwell on that too much). This is the HTML markup I have: <div id="modal-boxes"> < ...

Using JavaScript to eliminate brackets

When a map is clicked, I have a function that retrieves GPS coordinates. However, the result is currently displayed in brackets (). It is necessary to eliminate the brackets. function onClickCallback(event){ var str = event.latLng var Gpps = str / ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Error encountered: jquery form validation fails to register changes

I am currently developing a calculator-like code where users will submit a form multiple times, and I need to save the result of calculations only if there are changes in the form. For instance, when a user clicks the "Calculate" button for the first time, ...

Using a JavaScript variable to be displayed in a PHP code

Can someone please help me troubleshoot this code? I am attempting to display a JavaScript variable in PHP after applying a regex, but I keep getting the error Uncaught TypeError: document.getElementById(...).html is not a function $.post('display.ph ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

What could be causing my button to not capture the value of this input text field?

After clicking the button, I am trying to log the value of the input text field in the console. However, it just shows up as blank. Despite checking my code multiple times, I can't seem to figure out why. Any insights would be greatly appreciated! &l ...

Graphs vanish when they are displayed in concealed sections

Looking for a way to toggle between two charts (created with charts.js) by clicking a button? Initially, I had them in separate divs, one hidden and the other visible: <div id="one"> <canvas id="myChart1" width="400" height="400"></can ...

Website: Showcase Opentok using a Picture-in-Picture design

Currently, I am utilizing Opentok.js and my objective is to showcase both the subscriber and publisher within a Picture-in-Picture layout. I require this setup to be responsive and retain its aspect ratio when resizing the window. Additionally, I need gu ...

Setting up flowplayer for multiple div elements: a tutorial

I have a collection of videos and I am trying to set up the player for each div that holds a video. When constructing the divs in my JavaScript code, it looks like this: <div id="player+{{$index}}"></div> // The "player" + index is generat ...

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

Check for the presence of an Outlook add-in within a web application

I'm having trouble determining whether my hosted web application is being accessed through a browser or from within the Outlook 2013/2016 client. I have developed a web application that offers different functionalities depending on whether it is acce ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Error: The term "Particles" has not been defined

I'm attempting to integrate code from a website into my project, but encountered an error when the particles failed to run after adding it. I downloaded and installed particle.js from "https://github.com/marcbruederlin/particles.js/issues" for this pu ...

The search text box is mysteriously absent from each column in the datatables

I am utilizing jQuery Datatables to construct a table with data retrieved from MySQL. This is how my table appears: LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, QA_CONTACT_NAME, QA_PROCESS_NAME, CURRENT_QTY, Date, Temp ...

How can I find the week of the month using Moment.js? (similar to Google Calendar)

Currently leveraging the fantastic features of Moment.js, I am facing a dilemma. How can I determine which week of the month a particular date falls into? The documentation for Moment js only seems to provide information on "week of year." For instance, if ...

Sorting method in Ext JS 6.2.0 using mode

Seeking clarification on the sort([field],[direction],[mode]) method in Ext JS 6.2.0. Can someone explain the distinction between append, prepend, replace, and multi as mentioned in the documentation available at this link? I am unable to find a clear expl ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...