What is the best way to generate an array or multiple arrays dynamically using JavaScript?

I am currently working on a project where I need to dynamically create arrays to store elements based on certain conditions. Specifically, I want to create an array for each occurrence of a specific element (in this case, "bank"). The first occurrence should go into the first array, the second into the second array, and so on. Once all elements are placed in separate arrays, I then push them onto a main array.

My question is, can I generate these arrays with unique names dynamically, such as Bank_1, Bank_2, and so forth? And is this approach the correct way to solve this problem?

var bankcontainer = [];
var bank = [];

for(let i = 0; i < length; i++) {
    let bankname = data.periods[0].decisions[i].bank;
    bank[i] = [];
    bank[i].push(bankname);
    bankcontainer.push(bank);
}

For example:

// Input:    
[{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

// Result:
{ bank_1: ["team1"], bank_2: ["team2"], bank_3: ["team3"] }

Answer №1

const teams = [{ name: "team1" }, { name: "team2" }, { name: "team3" }]

console.log(
  Object.fromEntries(
    teams.map(
      (value, index) => [`team_${++index}`, value.name]
    )
  )
)

Answer №2

Loop through the array using Array.map() and generate a pair of [key, value] for each item, then transform them into an object with Object.fromEntries():

const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

const result = Object.fromEntries(
  data.map((o, i) => [`bank_${i + 1}`, o.bank])
)

console.log(result)

If Object.fromEntries() is not available, you can utilize Array.reduce():

const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

const result = data.reduce((r, o, i) => {
  r[`bank_${i + 1}`] = o.bank;

  return r;
}, {})

console.log(result)

Answer №3

this code snippet dynamically generates bank names

const bankcontainer = [];
let bank = [];

for (let i = 0; i < length ;i++)
{
  let bankname = data.periods[0].decisions[i].bank;
  const dynamicBank = {};
  dynamicBank["bank_" + i] = [];
  dynamicBank["bank_" + i].push(bankname);
  bank = dynamicBank["bank_" + i];
}
bankcontainer.push(bank);

Answer №4

Achieving this is definitely doable:

const myFinancialInstitutions = {};
const institutions = ['Bank of America', 'Goldman Sachs', 'Stackoverflow Credit Union', 'Chase', 'Capital One 360'];

for (let i = 0; i < institutions.length; i++)
{
  myFinancialInstitutions['Institution_' + i] = [institutions[i]];
}

console.log(myFinancialInstitutions);

Answer №5

let teams = [{ name: "team1" }, { name: "team2" }, { name: "team3" }];
let teamResults = {};
teams.forEach(
    (team, index) => { 
        teamResults[`team_${index + 1}`] = [team.name]; 
    }
);
console.log(teamResults);

Answer №6

The map() function is a powerful tool for manipulating objects in JavaScript, as demonstrated below:

let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];

newData = data.map((item, index) => {
return {['bank_' + index] : [item.bank]}
})

console.log(newData);

Answer №7

Utilize forEach loop on a dataset to generate a unique identifier based on the position, as illustrated below:

    let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
    let newData = {};
     data.forEach((item, index) => {
    newData['bank_' + (index+1)] = [item.bank];
    })

    console.log(newData);

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

PHP array syntax with square brackets at the beginning

Need some help with WordPress functions: $options = (array)get_options('value'); I'm able to retrieve an array using this method. Can anyone explain how it actually works? Thank you in advance. ...

Some Node methods are absent in MongoDB

I'm a newcomer to Mongo and I've been facing some difficulties with the basics. The code provided below reveals that db.getCollectionNames is returning as undefined, along with db.foo.find() and db.foos.find() both causing errors even though the ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Unlocking Column Data Tooltips in Angular Datatables: A Step-by-Step Guide

I have a single datatable and was wondering how to implement tooltips for when hovering over table cells. I tried the following code snippet, which successfully populated the tooltips. However, I am interested in achieving the same functionality using Angu ...

Tips for integrating AudioControl with Phonegap

I couldn't find a suitable plugin, so I decided to create my own. My goal is to activate silent mode using a JavaScript command, however, I am encountering an error with the undefined method getSystemService. It seems like there may be a problem with ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

What is the functionality of JavaScript RGB color pickers that do not use HTML5?

After inquiring about how HSV color pickers work, I am now curious about the inner workings of RGB color pickers using JavaScript. Specifically, those that do not utilize the HTML5 Canvas API. Could someone provide insight into the concept behind these typ ...

Patiently awaiting the completion of the entire page loading process

When using the methods below, we can determine if the entire page has finished loading. Sys.sleep(5) or remDr$executeScript("return document.readyState == 'complete';") or remDr$setTimeout(type = "page load", milliseconds = 10000) However, ...

Incorporating styles to dynamically generated elements in JavaScript

I am dynamically generating input fields with a delete button "x" that allows users to remove the field. The layout looks similar to this Here is the Javascript code: $(document).ready(function() { // When the add_button is clicked $('#add_c ...

Comparing OLOO and OO in ReactJS for front-end web development

After reading Kyle's book, I found it to be extremely informative. However, I am a bit perplexed by the discussion in "You Don't Know JS: this & Object Prototypes". The series argues that the "Object Linking to Other Object" design pattern is cl ...

Tips on creating adaptable images for mobile viewing

My coding conundrum involves the use of two columns - one for an image and the other for a description of that image. However, when viewing my site on mobile devices, the image is cut off at only half its height. Adjusting both columns to col-sm-6 results ...

Having trouble with transferring data from javascript to php for generating a PDF file

Currently, I am utilizing JavaScript to gather information from a form submitted by a user. This data is then sent to PHP in order to generate a PDF using FPDF. However, I am facing an issue where I want the browser to prompt the user to either save the PD ...

With the power of jQuery, easily target and retrieve all label elements within a specified

Currently, I'm working on developing a function that should be executed whenever any of the labels for a particular group of radio buttons are clicked. So, I need a way to reference all the labels in this radio button group. In my search for a soluti ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

Using AJAX to send an array of values to a PHP script in order to process and

I have very little experience with javascript/jquery: My ajax call returns entries displayed in an html table format like this: Stuff | Other stuff | delete stuff ------|----------------|------------------------- value1| from database | delete this ...

Customizable positioning of hover messages while ensuring messages do not extend past the boundaries of the object

Within an application featuring a dynamic assortment of plots rendered and scaled within a fixed div, I am grappling with the final scenario whereby, in a layout of plots spanning multiple columns and rows, the message should be contained within the groupi ...

Nodemailer contact form malfunctioning

I've been working on setting up a contact form in React and utilizing nodemailer to send messages to my email, but I seem to be encountering some issues. I have a server.js file located in the main folder along with Mailer.js which contains the form c ...

Tips for loading nested JSON data into an Angular Material dropdown list

My task involves extracting data from a JSON object and displaying the difficultyLevel. Despite several attempts, I have been unable to achieve the desired outcome. What changes should be made to the HTML file? const ELEMENT_DATA: data = { questions ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

What is the best way to customize the style using a CSS class?

Is it possible to alter a specific style with a CSS class using jQuery or JavaScript? For example, if the HTML looks like this: <tab> <a class="anchor">a</a> </tab> And the CSS looks like this: a {border:1px} .anchor {color: ...