What is the best method to set variables to zero using this array in JavaScript?

I am looking to extract strings from an array and set them all to zero.

The original array consists of:

var myArray = ["apple", "banana", "cherry", "date"];

The expected outcome should be:

var apple = 0;
var banana = 0;
var cherry = 0;
var date = 0;

I was thinking of using a loop to go through the array, create new variables, and assign zero to them, but I'm unsure about the syntax.

What would be the best way to achieve this?

Just for your information, I plan to utilize these zeros as counters later on.

var myArray = ["apple", "banana", "cherry", "date"];
var counterArray = [];

$(document).ready(function() {
  for (var i = 0; i < myArray.length; i++) {
    var value = 0;
    counterArray.push(value);
  };
  console.log(counterArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №1

I was thinking about iterating through the array and creating new variables equal to zero, but I wasn't sure how to do that.

All the variables are part of the window object. So, you can achieve this in the following way:

var anArray = ["hello", "can", "you", "hear", "me"];
for (i = 0; i < anArray.length; i++)
  window[anArray[i]] = 0;

// Console.log
console.log(hello);
console.log(can);
console.log(you);
console.log(hear);
console.log(me);

This method works perfectly! Give it a try and see the results in your console. :)

Answer №2

This method can also be used to achieve the desired outcome. View example here

For further information, you can refer to this source

function sampleData() {
  var newArray = ["hello", "can", "you", "hear", "me"];
  var firstObject = {};
  for (var j = 0; j < newArray.length; j++) {
    firstObject[newArray[j]] = 0;
  }
  return firstObject;
}

alert(JSON.stringify(sampleData()));

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

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

I am currently developing a user-friendly bug reporting system that is fully functional. However, I have encountered a persistent error message in the console related to Discord.js that I am determined to resolve

In coding this bot, we are using the Discord.js library and some custom functions to handle bug reports from users. The bugreport command allows users to submit their reports, which are then sent to a specific channel for further action. However, we encou ...

Transform an array of integers into a mapping of values and corresponding IDs for selected values

I've been able to successfully load values from my API into react-select for single select, but I'm encountering some issues with multi-select. const fetch_companies = () => { API.get("/companies") ... data = data.map(({ id: ...

Enhancing productivity with tools for developers and effortless tab navigation

During my development process, I always keep the developer tools open on one or more of my tabs. However, I noticed that when I switch to a tab where the developer tools were not previously open, a resize event is triggered. Strangely, this event causes el ...

Challenges arise when attempting to pass array data from Ajax to Google Maps

I'm facing an issue with my Google map. I have a data array that is dynamically returned, and I want to use it to add markers to the map. However, the markers don't work when I pass the data variable to the add_markers() function. It only works i ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

Fix image that won't load in Firefox

My website features an <img /> element that initially lacks a src attribute. The src is added dynamically using JavaScript at a later point. While Chrome hides it, Firefox displays an empty space: https://i.sstatic.net/3eZJ4.png Is there a way to p ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

When using React, it's important to verify if the page has been refreshed before updating the local storage based on the GraphQL query. If the page

Currently, I am working on implementing a hit counter feature that increments each time a user clicks a button. The setup involves GatsbyJS with React and utilizes a lambda function to store the count in FaunaDB. Additionally, the client-side functionality ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

What is the process of transferring data from one div to another div (table) using AngularJS?

In my quest to enhance my table with JSON data upon clicking the + icon, I am faced with two sections: Pick Stocks where stock names and prices (retrieved from data.json) need to be added to the table found in the Manage Portfolio section. First Section h ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Issue with extended waiting times in polling

I am currently working on a chatroom using the long poll method. However, I'm facing an issue where every time a long poll occurs and I refresh the page in Chrome or try to send another async request, everything times out. This means I can't load ...

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...