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

What is the procedure in AngularJS to obtain an ID from a URL? My current approach involves utilizing Restangular for communication with REST APIs

I have been successfully using Restangular to retrieve data from the backend. The URLs I was hitting used to provide the data in the following format: For example, when I hit http://mysite/responses/, the responses were in the following structure: [ ...

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Variable Stores the Results of Node.js http.request

Hello everyone, I've been working on a project where I need to pass the results from an https.request in my node.js code to a variable. The https.request is set up to communicate with a SOAP API and receive the response successfully. My main objectiv ...

Unable to establish connection via web socket with SSL and WSS in JavaScript

Below is the code I used to implement web socket: try { console.log('wss://' + hostname + ':' + port + endpoint); webSocket = new WebSocket(webSocketURL); webSocket.onmessage = function (event) { //c ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

When you access the `selectedIndex` property in JavaScript, it will return an object of type `HTMLSelect

I am currently working on a piece of code that retrieves the value from dropdown list items and then displays it in the document. To proceed, please select a fruit and click the button: <select id="mySelect"> <option>Apple</option ...

Changing the Position of HTML Scripts in React

I am facing an issue where I need to relocate an external script within a specific section of my page. However, I am unable to access the CSS attributes associated with this item. It seems that it is displayed as an iFrame, making it difficult to modify th ...

Utilizing the map function to display elements from a sub array

I'm struggling to print out the comments using the map function in this code: class Postcomment2 extends React.Component { uploadcomment = () => { return this.props.post.comments.map((comment) => { return <div>{comment["comment"]}< ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Can you explain how to utilize prop values for setting attributes in styled-components v4 with TypeScript?

Overview Situation: const Link = styled.a` border: solid 1px black; border-radius: 5px; padding: 5px; margin: 10px 5px; `; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>; const LinkAsButton = styled(Link).attrs<ButtonP ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Exploring the various methods of creating controllers and services in AngularJS and understanding the rationale behind each approach

I've been observing various instances of controller and service creation in AngularJS and I'm feeling perplexed. Could someone elucidate the distinctions between these two methods? app.service('reverseService', function() { this.re ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...