javascript batch insert new key values

Is there a more elegant way to set multiple keys of an array in JavaScript?

The current code may not be aesthetically pleasing, but it seems to be the only solution that works.

var listData = [];
listData['today'] = [];
listData['data1'] = [];
listData['data2'] = [];
listData['data3'] = [];
listData['data4'] = [];
listData['data5'] = [];
listData['data6'] = [];
listData['data6'] = [];

I attempted to initialize the array in a different way:

function initArray(arr, keys, defaultValue) {
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        delete arr[key];
        arr[key] = defaultValue;

    }
    return arr;
}

However, after setting the array, I encountered issues when adding data:

When trying to insert data into the array using commands like listData['data1'].push(datalist[i].num) listData['data2'].push(datalist[i].num), the resulting array displayed duplicates of 'data1' and 'data2' entries.

If anyone has suggestions on how to efficiently add keys to an array, I would greatly appreciate the assistance.

Answer №1

Consider adjusting the push function in this code snippet.

var dataList = [];
var values = [ 'Monday', 'Tuesday', 'Wednesday' ]; 
initializeArray(values);

function initializeArray(elements) {
    for (j=0; j<elements.length; j++) {
        var y = elements[j]
        dataList.push(y)
    }
}

Answer №2

Opt for utilizing an object in place of an array:

var dataObject = {};
var properties = ['today', 'value1', 'value2'];

function createEmptyObject(obj, keys, defaultValue) {
  keys.forEach(key => {
    obj[key] = [];
  })
  return obj;
}

console.log(createEmptyObject(dataObject, properties, []));

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

The Node.js engine isn't updating to support compatibility with Firebase functions

Encountered First Failure Below is the content of package.json "engines": { "node": "8.0.0" }, Error: The engines field in the functions directory's package.json is unsupported. You can choose from: {&quo ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

The error message "Unknown provider: groupByFilterProvider <- groupByFilter error" is displayed when trying to use the angular.filter's groupBy filter

I am new to Angular and I'm trying to implement the `groupBy` filter from angular.filter but I'm having trouble including it in my project. I followed the first two steps outlined in the documentation at https://github.com/a8m/angular-filter#grou ...

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

Determine whether a specific letter provided by the user is present in a character array through a Java statement

I'm currently working on a program that prompts a user to input a string, which is converted into a char array, and then input a single letter. The program is then supposed to check if the string contains that specific letter. Below is the code that I ...

After delving into the depths of a category tree, the multidimensional array reveals its

I am currently working on creating a category tree that can accommodate any number of sub-categories for each main category. I found some code online that I adapted for my CodeIgniter project, but I'm struggling to achieve the exact result I desire. ...

Mastering the art of utilizing callback functions

As a newcomer to Javascript and Jquery, I am still learning the basics. One thing that confuses me is how javascript executes each line as it encounters it. In a certain scenario (when my value is greater than 9), the custom alert will trigger and the wind ...

How can I retrieve the input value on the current page using PHP?

Hey there, so I'm pretty new to PHP and I have a question. Is it possible to retrieve the input value from an existing input field on a page using PHP when the page loads, and then assign that value to a variable? For instance, let's say I have ...

Mobile Drag and Drop with JavaScript

While experimenting with a user interface I created, I utilized jQuery UI's draggable, droppable, and sortable features. However, I observed that the drag and drop functionality does not work in mobile browsers. It seems like events are triggered diff ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Can someone recommend a design pattern to implement in React?

I have encountered a challenge while working with over a thousand svg elements. Whenever I try to remove, update, or select a single element, it consumes a significant amount of time. The issue lies in the fact that when I modify or delete a specific svg e ...

Issues with Django Site Search Functionality

Currently working on a Django project, I have encountered an issue with the search bar on my localhost site. Despite adding the search bar, it fails to return any results when provided input. Upon inspecting the page source, I discovered some unfamiliar li ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Using jQuery to trigger a click event on a radio button prevents the button from being checked

Having trouble with using the .trigger("click"); function on radio buttons to activate a button in a form. When I use the code below, the button is triggered as expected. However, it seems to be interfering with the radio button, causing it to appear chec ...

How to emphasize a portion of an expression in AngularJS using bold formatting

I have a specific goal in mind: to emphasize part of an angular expression by making it bold. To achieve this, I am working with an object obj which needs to be converted into a string str. obj = $scope.gridOptions1.api.getFilterModel(); for (var pr ...

Transferring the mistakes to the final return statement

I am currently working on a script that checks if a username is available or already taken. When the username is found to be taken, I need to assign an error message to my errors object. However, I am struggling with passing these errors from the inner if ...

What is the most effective method for implementing multiple textures in three.js?

After recently transitioning to three.js as my renderer, I am eager to establish a texture mapping system. However, determining the best practice for this task is a bit uncertain for me. Here is the scenario I am dealing with: My levels consist of numero ...

Retrieving a JSON object using a for loop

I'm working on a basic link redirector project. Currently, I have set up an Express server in the following way: const express = require('express'); const app = express() const path = require('path'); const json = require('a ...

Are these two glob patterns distinct from each other in any way?

images/**/*.{png,svg} images/**/*.+(png|svg) After running tests on both expressions, it appears that they generally yield identical outcomes. However, it is crucial to confirm that they are indeed equivalent. ...