Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'].

function calculateStats() {

    var obj = {}

    var deviceId = "34534";

    for (var i = 1; i <= 21; i++) {

        var loo = i.toString();

        console.log(loo);

        obj[deviceId] = ['e' + loo + '.kwh'];

        console.log(obj[deviceId]);
    }

}

Answer №1

Modify the line below

obj[deviceId] = ['e' + loo + '.kwh'];

Using

(obj[deviceId])?obj[deviceId].push('e' + loo + '.kwh'):obj[deviceId]=['e' + loo + '.kwh'];

Answer №2

Check out this potential fix:

The problem stemmed from the fact that you kept replacing obj[deviceId] with an empty array.

function calculateStats() {

    var myObject = {}

    var uniqueId = "357803045265259@rayleigh";
    
    myObject[uniqueId] = [];

    for (var index = 1; index <= 21; index++) {
    
        var value = index.toString();

        console.log(value);

        myObject[uniqueId].push('e' + value + '.kwh');

        console.log(myObject[uniqueId]);

    }

}

https://jsfiddle.net/q651uhde/

Answer №3

function generateData() {

var myList = [];

var deviceID = "2222@bohr";

for (var j = 1; j <= 30; j++) {

    var num = j.toString();

    console.log(num);

    myList.push('f' + num + '.watt');


}

console.log(myList);

} myList contains your data, is that the desired outcome?

Answer №4

To start, create an array and then add each string to it individually. There's no necessity to change the index to a string since it will automatically be converted to a string when added to the array.

function generateData() {

  var container = {};
  var id = "123456789";
  container[id] = [];

  for (var num = 1; num <= 15; num++) {
    container[id].push('value' + num);
  }

}

DEMO

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

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

Prevent selection of rows in the initial column of DataTables

I am working on a basic datable, the code can be found here JS: var dataSet = [ ["data/rennes/", "Rennes", "rennes.map"], ["data/nantes/", "Nantes", "nantes.map"], ["data/tours/", "Tours", "tours.map"], ["data/bordeaux/", "Bordeaux", ...

Add an array into another array using a for loop, with the first result being duplicated

In this loop, I am facing an issue while trying to insert an array into another array. Here is the code snippet: function convertFormToArray(form){ var temp={}; var question={}; var allQuestions=[]; for (i = 0; i < form.length; i++ ...

Strip the pound symbol from the end of a URL during an AJAX request

When I click on the News tab in my Rails application (version 2.3.4 and Ruby 1.8.7), an Ajax call is triggered to load data. <a href="News" onclick="load_feed();"><u>Show More...</u></a> <script> function load_feed() { $.a ...

Utilizing Hyperlinks in jQuery DataTables Cell with Data Pulled from Mysql Table

I have a question that builds upon the one before it: How to display a hyperlink in a cell with jQuery DataTables There is also a Fiddle link provided My current query revolves around implementing hyperlinks when fetching data from a MySQL database table ...

The functionality of using multiple inputs with Google Places API is not functioning as expected

Having trouble with the Google Place API. I am unable to set up 2 input fields with autocomplete. The first input is populated from a payload received from the backend, while the second input is within a Bootstrap modal. I have tried various solutions fou ...

Develop a COM API, or equivalent, tailored for a Node.js application

I have developed a JavaScript application that is designed to run on node.js. Is there a way to create a custom COM API or something similar for a Node.js application? For instance, in languages like C, C++, C#, etc., you can develop an application and t ...

Opting for Mysql over MongoDB as the provider in Next.js with Next-auth

Exploring the Next.js framework for the first time, I've dived into using Next-auth to handle sign-up/login functionality based on the provided documentation. My experience so far has been smooth, especially with the MongoDB provider as recommended i ...

The componentDidUpdate method ensures equality between the previous and current states

Within a dashboard, the layout data for each module (utilizing react-grid-layout) is stored separately from the module data and both are saved in a database. The Dashboard component state holds the current module data and layout data. I'm attempting t ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

Looking for assistance with REGEXP to handle a 404 path rendering issue

I am attempting to utilize REGEXP in order to display a 404 page within a react app based on the path, but I am struggling to make it work. This is the specific REGEXP pattern I am trying to achieve: The entire path should not be '/' and should ...

Should You Ajaxify Your Website?

Absolutely loving the way Ajax can transform a web app into something that performs like a desktop application. The concern, however, arises when dealing with high volume sites. Currently working on an intranet-based database app meant for only 2-4 users a ...

Shuffle arrays in sync multiple times using various seeds in Numpy

Is there a way to shuffle multiple numpy arrays with the same number of rows in unison, and then reshuffle them with different random seeds? I've been struggling with this issue and tried a few methods. I initially used the solution found on Stack Ov ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

Why does the type of obj.getClass() in Java return Class<?> instead of Class<? extends T>?

Question: <T> void foo(T obj) Why is the type of obj.getClass() Class<?> instead of Class<? extends T> in a generic function like this? Even though the code below works fine: String foo = ""; Class<? extends String> fooClass = f ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

javascript update HTML content

Hello, I am trying to call a function called changeDivHTML which passes an image. <a href="javascript:void(0)" onclick="changeDivHTML(<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'>)"> This function ad ...

Attach a click event handler to a D3 element

Upon loading the page, the nodeClick() method is called without any clicking action. How can I adjust it so that the nodeClick() function is only triggered when I click on the element? Here is the code snippet: var node = svg.selectAll(".node") .on( ...

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...