Is there a way to create a dictionary in Javascript with all keys pointing to the same value?

I have a scenario where I need to convert an array into an object like this:

let arr = ['ABC', 'DEF']

The desired transformation is:

let obj = {"ABC": 0, "DEF": 0}

Can someone guide me on how to achieve this using ES6 syntax?

let arr = ['ABC', 'DEF']
arr.reduce(x => ({[x] : 0 }))

I tried the above code snippet, but it only gives me {"ABC": 0}

In essence, I want to set all values in the array to a default value of 0. The array could be of any length.

Any help would be appreciated! Thank you!

Answer №1

To simplify the process, just use a basic loop like this:

const items = ['123', '456'];
const data = {};
for (const item of items) data[item] = 0;

If you're looking for a more advanced solution, consider using Object.fromEntries:

Object.fromEntries(items.map(item => [item, 0]))

Answer №2

Creating individual objects like a map is not the most efficient way. It's better to return the object each time.

const arr = ['ABC', 'DEF']
const result = arr.reduce((o, k)  => ({[k] : 0, ...o }), {});
console.log(result)



const result2 = arr.reduce((o, k)  => (o[k] = 0, o), {});
console.log(result2)

Answer №3

const newObj = arr.reduce((acc, val, idx) => {
  acc[val] = 0;
  return acc;
}, {})

I trust this solution will be beneficial to you. Feel free to reach out if you encounter any challenges.

Answer №4

To implement this functionality, simply utilize the Array.reduce method with an empty object declared as the initial value in the code snippet below:

var result = ["123","456"].reduce((x,y) => (x[y]=0,x),{});
console.log(result);

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

Updating GridView row only if there are changes, the value remains unchanged in JavaScript. Disappointing

Incorporating a gridview (ASP.net) inside an update panel, I included a "Save" button that triggers a loop through all the rows of the grid view to pass data to a stored procedure for updating each row. However, this process proved to be slow and resulted ...

What is the best way to display the elements of an array within an HTML div element?

I've been trying to display the contents of an array in a div container on my HTML file, but I'm stuck. Here's what I currently have: function printArray() { var $container = $('.container'); $container.html(''); ...

Function to handle click events on Highcharts column series points

Just recently, I posted a query regarding Highcharts column charts drilldown. I have discovered that within the click event of the point object, you can determine which column was clicked. I have integrated this functionality into my code, but unfortunatel ...

Is it possible to manually input values when printing a PDF instead of pulling them from the main HTML?

I am facing a challenge in adding a "Print PDF" option to my website because it is built using Ext.js, and therefore the code is not in HTML. Despite searching for ways to print a PDF from the site, all solutions I found involve using HTML. Is there any li ...

Submitting an HTML form to trigger a PHP function through AJAX

I am currently working on a task that involves POSTing an email address entered in an HTML form to a PHP script for storage in a database. The script should also handle error messages if the user inputs an invalid email address. I want to make this process ...

Tips for keeping a div element at the top of the page

I am looking to have a div stick to the top of the page when someone scrolls down When the page is scrolled, the green div with class stickdiv should automatically stick to the top var left = document.getElementsByClassName("stickdiv"); for( var i = 0; ...

Connecting Angular directive to a controller

While diving into some Angular JS tutorials, I decided to apply what I learned in the Ionic framework. Unfortunately, I hit a roadblock when attempting to create a reusable HTML control because the model isn't syncing with the view as expected. Here&a ...

Aligning Page to a Specific Element Without Changing the DOM or Utilizing References

My goal is to easily scroll to a specific element using #: <a href="#element">Element</a> <div name="element" /> While this method works effectively, it always takes me to the top of the element. I would prefer to have the element cent ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

Discovering identical values within an array along with the differences between them

For instance: [1, 4, 9, 78, 42, 4, 11, 56] In this scenario, the duplicated number is 4 and the difference is 3. Although I utilized the array for every array element, I aim to enhance this query for better optimization. ...

Abstraction of middleware functions

After reviewing my middleware Express functions, I realized that there is repeated code. The first function is as follows: const isAdmin = async (req, res, next) => { try { const requestingUser = await knex('users') ...

Set the text field to be editable or readonly based on certain conditions

Is there a way to conditionally enable or disable an editable field (edit/read only)? I have tried using session role from the database to set conditions on the text field, but I am unsure of how to proceed... <?php include('session.php'); ?& ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...

View the gathered HTML content in a fresh browser tab

I'm looking to enhance the reporting system on my website by sending an AJAX request with a progress bar. The server will collect the necessary data, convert it into HTML, and then send it back to me. Upon successful completion of the AJAX request, I ...

Tips for selecting a specific range of values in an array post sorting

After spending countless days working on this program, I am still facing several challenges. The task at hand is to develop a program capable of sorting using Bubble Sort, Selection Sort, Insertion Sort, and Shell Sort algorithms. The program should read ...

"Utilize Ajax and PHP to seamlessly upload a PDF file directly into a MYSQL database

I am trying to figure out how to upload a pdf file from user input into my MySQL database. I have provided code that displays a user registration form with the option to upload a PDF file. My goal is to use AJAX to post this data to a PHP script for storag ...

Adjusting <Video> source according to screen dimensions using JavaScript

I am currently experimenting with developing a website locally on my computer using bootstrap. One unique feature I am working on is having a <video> as the header of the site. My goal is to have the video display at full width and height on mobile ...