Using plain JavaScript, adding an element to an array by pushing the value of a string variable in an index position rather than pushing the

I have the following JavaScript code snippet:

let array = [];
const datas = [
 'name1',
 'name2',
 'name3',
];
 
async function getData() {
    datas.forEach((data) => {
      let myData = data.name;
      if(!array.includes(myData)){
        array.push(myData);
      }
    })

    let result = await array;
    
    console.log('Result', result);
};

getData();

This code returns an array containing strings like:

['name1','name2', 'name3']

I want to convert each index of the array into an empty array, so it looks like this:

['name1': [], 'name2': [], 'name3': []]

Is there a way to achieve this using plain JavaScript?

Answer №1

It seems that a solution like the one below may suit your needs

let object = {};
const elements = [
 'item1',
 'item2',
 'item3',
];
 
function extractData() {
    elements.forEach((element) => {
      object[element] = []
    })

    console.log('Output', object);

};

extractData();
Output { item1: [], item2: [], item3: [] }

Hint: Array keys must be numeric indexes only

Answer №2

Instead of using an array, you could opt for an object and assign each name as a key like shown below:

let obj = {};
const names = [
 'John',
 'Alice',
 'Bob',
];
 
function getData() {
  names.forEach((name) => {
    if(!obj[name]){
      obj[name] = [];
    }
  })
  console.log(obj);
}

getData();

This will result in an object structure like this:

{
  John: [],
  Alice: [],
  Bob: []
}

It is important to ensure that each name is unique.

If you prefer to have an array returned, you can construct an array of objects as demonstrated below:

let array = [];
const names = [
 'John',
 'Alice',
 'Bob',
];
 
function getData() {
  names.forEach((name) => {
    array.push({
      name: name,
      data: []
    });
  })
  console.log(array);
}

getData();

With this approach, the resulting array would look like this:

[{
  data: [],
  name: "John"
}, {
  data: [],
  name: "Alice"
}, {
  data: [],
  name: "Bob"
}]

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

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

What is the best way to execute the app functions, such as get and post, that have been defined

After creating a file that sets up an express middleware app and defines the app function in a separate file, you may be wondering how to run the app function. In your app.js file: const express = require('express') const cors = require('c ...

Leveraging LevelGraph with MemDOWN

I've been experimenting with using LevelGraph and MemDOWN together, but I've noticed that my put and get queries are significantly slower compared to using the filesystem directly with LevelUP. It seems like there might be some mistake in my setu ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

Import data into Bootstrap table from an external source

I am having trouble styling the table loaded from the table.html file onto the index page. Even after loading the table, the styles from bootstrap classes are not applied. What could be causing this issue? Importing bootstrap libraries directly into the ta ...

Using val() on a checkbox will give you an element, not a string literal

How can I retrieve only the literal values of all checked checkboxes without any additional data? My current approach is: $('input:checked').map(function() { return $(this).val(); }) The result that I am getting looks like this: e.fn.init[1]0 ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

What is the best way to limit the number of items shown in a cart dropdown using JavaScript

I have a shopping cart feature added to my ecommerce web app. Within the header, there is an icon of a cart. When clicked, a dropdown appears showing the items added to the cart. However, if I have 10 items in the cart, the dropdown becomes too lengthy to ...

What is the reason for the identical nature of these two arrays?

Looking to make a copy of my list and then sort it without altering the original in Python. Below is my code snippet: def swapBySoting(arr): newArr = arr newArr.sort() swap = 0 for i in range(len(arr)): if arr[i] != newArr[i]: ...

Is there a way to display a React component containing an array that is constantly changing due to an external function?

I am facing a challenge involving a component that needs to render an array of divs. The requirement is to add another div after a certain external function is triggered. This function must be declared outside the component for export purposes. The issue ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Reasons for aligning inline elements with input boxes

I am facing a challenge with aligning a series of inline elements, each containing an input text box, within a single row. The number and labels of these input boxes can vary as they are dynamically loaded via AJAX. The width of the div housing these inli ...

Maintain the previous state in AngularJS using ui-router

My goal is to preserve the current state of the view, not just the URL and parameters. I am looking to save the entire view along with its scopes. Specifically, I am working on creating a search system similar to Facebook's, but with a unique twist. I ...

Display an error message if the input field is empty, then conceal the message once the input field is filled

Can anyone assist with a Vue.js app issue I'm facing? Currently, when the search input is empty, an error message appears - which is okay. However, I want to hide this error message as soon as the user starts typing in the search field. The code for m ...

ngAnimateSwap - animations do not function as intended when boolean expressions are utilized

I adapted the original ngAnimateSwap demonstration from the AngularJS documentation to utilize a boolean expression for triggering the slide animation. Initially, I anticipated the banner to switch back and forth between 'true' and 'false&a ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...