Generating multiple arrays within a multidimensional array using Javascript in a dynamic way

I have a single variable called $arrayQuantity that holds a changing value. This value determines how many item arrays should be created within the $itemsContainer array when the page is loaded.

For example:

//In this example, I want to create 3 `item` arrays inside the *itemsContainer* array.
//Each of these arrays will contain two dynamic values: `object_name` and `quantity`.

var object_name;
var quantity;
var item = [object_name, quantity];
var arrayQuantity = 3; 
var itemsContainer = [];

//Below is an example of filling the array with dynamic data.
itemsContainer = [["Chair", "2"]["Table", "5"]["Glass", "8"]];

How should I go about solving this issue?

EDIT :

The dynamic data for object_name and quantity is determined based on which button is pressed on the screen (this information is not relevant to the question).

If the object_name already exists within the array, only the quantity should be updated in order to avoid duplicate entries of the same object_name.

Answer №1

It is unclear where the data for object_name and quantity originates from, but one approach could be to create a loop that goes through the number of times specified in arrayQuantity and adds a new array to itemsContainer.

var arrayQuantity = 3;
var itemsContainer = [];

for(var i=0; i < arrayQuantity; i++) {
    var arrItem = ["itemName", Math.floor((Math.random() * 10) + 1)];
    itemsContainer.push(arrItem);
}

console.log(itemsContainer);

If you're unsure about the source of your values, this code snippet may steer you in the right direction.

>> Example on JSFiddle

-mbp

Answer №2

Begin by creating the inner array and inserting it into the outer array

var objects = ["Desk", "Lamp", "Bookshelf"];
var quantities = ["3", "6", "10"];
var storageContainer = [];
var totalObjects = 3;
for (var j = 0; j < totalObjects; j++) {
    var item_name = objects[j];
    var quantity = quantities[j];
    var stored_item = [item_name, quantity];
    storageContainer.push(stored_item);
}
console.log(storageContainer);

For a more efficient method, consider using Array map

var objects = ["Desk", "Lamp", "Bookshelf"];
var quantities = ["3", "6", "10"];
var storageContainer = objects.map(function(obj, index){
    return [obj, quantities[index]];
});

To update a specific item in the container:

var item_name = "Desk";
var quantity = "99999";
for (var j = 0; j < storageContainer.length; j++) {
    if (storageContainer[j][0] === item_name) {
        storageContainer[j][1] = quantity;
    }
}

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

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Am I on the right track with my code for generating a mirror image of a 2D array?

// Function to mirror a two-dimensional array public int[][] Mirror(int[][] originalArray) { int[][] mirroredArray = new int[originalArray.length][]; for (int i = 0; i < originalArray.length; i++) { for (int j = originalArray[i].length ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

Eliminate a single character from an array in PHP

Looking to manipulate an array by removing all occurrences of 0.0 without using a loop: array ( [79] => 0.0 [80] => 0.0 [81] => 0.0 [82] => 0.0 [83] => 0.0 [84] => 0.0 [85] => 0 ...

Divide an array into smaller chunks using array_chunk dynamically, depending on the elements in

Is there a way to split an array dynamically, similar to the function array_chunk, but instead of specifying the size as an integer for the second parameter, can we use an array like different_sizes to define the chunk sizes? $input_sub_arr = range( ...

Utilize resources from webpack's bundled npm package assets

I've been racking my brain over this issue for quite some time now, and I'm starting to wonder if it's even achievable. Any assistance on this matter would be greatly appreciated! The npm dilemma I have an npm package that serves as a coll ...

Retrieve the date and month information from the data-date-format

Can anyone help me figure out how to extract only the date and month from a bootstrap date picker and assign them to variables? <div class="input-append date dp3" data-date-format="dd.mm.yyyy"> <input class="span2" size="16" type="text" id="R ...

The freshly generated input element is disregarding modifications to attributes

What is the reason for $("<input type='text' value='Foo' />").val("Bar") resulting in an object (as seen in the debugger console)? <input type="text" value="Foo"> Why doesn't the value change to "Bar" after bei ...

The ajax call I made is not retrieving any data, only returning an empty array

I am having trouble passing data from JavaScript to PHP through AJAX. Even though I have passed some data, the output is showing as an empty array. Can someone please assist with this issue? <html> <head> <title></title> ...

Is there a way to store the form data as a text file using jQuery or JavaScript and sending it to a PHP file?

I have created a basic html form with pre-filled information for demonstration purposes. Currently, when the form is submitted, it is saved to Google Docs successfully. However, I also want to save the form output to a text file on the server where the p ...

Utilizing EXTJS 5: Choosing between a tagfield or combobox to dynamically display and conceal form fields

I am looking to create a dynamic form that shows and hides fields based on the selection made in a multi-select combo box (tagfield). For each item selected in the combo box, there are hidden form fields associated with them. These fields have the proper ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

Issue with Laravel: Using `$request->all()` results in an empty array when called using JSON XHR

Having trouble using $.ajax and only the XMLHttpRequest for sending JSON to a Laravel controller. Keep getting 500 errors when attempting to make the request. Here's the method I'm using to send the data: const sendEdit = function(){ ...

Tips for securely utilizing a javascript API without exposing your API key

Newbie alert! I am currently working on an app that utilizes Here's Geocoding REST API through node.js with express. (I made sure to keep my api key hidden on the server side to prevent exposure to clients.) However, I have come to realize that in or ...

What is the best way to prepopulate form values in a Vue object?

Sharing my code snippet: HTML: <div id="user-panel"> <div class="text-center"> {{ fillItem }} </div> <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:s ...

From Objective-C to JSON to PHP array

I've been struggling with this issue for the past few days. My goal is to send an array to PHP, but I am encountering difficulties in receiving it as a post-variable named "json". I have tried various solutions and techniques, but so far, I have not b ...

Is it possible for the Jquery Accordion to retract on click?

Hello everyone, I've created an accordion drop-down feature that reveals content when the header of the DIV is clicked. Everything works fine, but I want the drop-down to collapse if the user clicks on the same header. I am new to JQUERY and have trie ...

ESLint is not performing linting even though the server is operational

I found a frontend template online and successfully installed all the packages using yarn. However, although I have an .eslint.json file in place and the ESLint extension is installed in Visual Studio Code, I am not seeing any linting errors. Below is the ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

How can Python be used to change the positions of characters using their indices?

Two arrays, encryted_message = [] and index_shuffle = [], are used in this encryption process. The encryted_message = [] array takes the user input and splits the words into individual characters, while the index_shuffle = [] array keeps track of the index ...