Transforming an array into an object by assigning the array values as the keys and setting the corresponding object values as empty

Currently, I am developing a web application using reactjs. In my project, I have an array defined as:

let arr = ["name","message", etc...];

My goal is to convert this array into an object that looks like the following:

let desired = { name:'', message:'' };

Despite trying different methods, unfortunately, none of them have achieved the desired result.

Answer №1

To assign an empty string to each value in the array, you can use the reduce method:

let arr = ["name","message", "etc"];
let desired = arr.reduce((acc, curr) => (acc[curr] = "", acc), {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Using ES5 syntax:

var arr = ["name","message", "etc"];
var desired = arr.reduce(function(acc, curr) {
  acc[curr] = "";
  return acc;
}, {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Answer №2

Give this a shot:

const items = ["title", "content", "description"];
const result = {};
for (let index = 0; index < items.length; index++) {
    result[items[index]] = "";
}
console.log(result);

Answer №3

Another option is to utilize the forEach() method.

let array = ['name', 'type', 'id', 'phone'];
let object = {};
array.forEach(item=>{object[item] = ''});

console.log(object);

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 Vue.js mixin is not functioning properly within the component as expected

I've created a mixin in Vue.js for a simple digital watch: var myMixin = { data () { clockInt: '', clock: '', currentTime: new Date() }, mounted () { this.intervalSetup(); }, ...

Receive a positive or negative data message through Ajax Response

Exploring Ajax for the first time, I am eager to incorporate database interaction using AJAX in JQUERY by connecting to a PHP script. $(function() { $.ajax({ type: "POST", url: "response.php", ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Looking for a standard ajax request handler for asp.net

My website is a mix of pages using asp.net ajax calls and prototype ajax calls. I'm looking for a way to intercept all ajax requests regardless of their origin so that I can run a custom client script after each partial postback. I want to keep this ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

Typescript - Conditional imports

When working with the moment-timezone module, one issue that arises is receiving a warning if it is included multiple times. In my specific case, I have a module that necessitates the use of this timezone functionality. Since I am unsure whether or not the ...

Generate a highcharts graph by utilizing AJAX and JSON data

I'm currently working on a website project that involves utilizing the Highcharts library to showcase a single line series chart. To obtain historical financial data, I have implemented AJAX to fetch information from yahoo finance using their YQL. Su ...

JavaScript code that generates a variable output

Hi there, I'm currently working on a project where I need to update some data using a dropdown box. My goal is to create a function that returns the variable ds or ds1 based on the user's selection. For example, if they choose "ds" from the dropd ...

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

Working with Postgresql: how to replace entire strings within JSON data by using delimiters

Is there an efficient way to perform a string replacement in PostgreSQL while considering specific conditions? The strings requiring replacement resemble https://my.oldserver.com/api/v1/images/929009-ee-cda-6-4227-83-e-4-80-fc-954730-b-6.jpeg?id=MQkvMjAyM ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

At times, Vue.js may encounter difficulties when attempting to load a component

Recently, a strange issue has been occurring in my production code. Although nothing has been changed, I am now receiving reports that occasionally a template fails to load causing the page to crash. I am currently using vue 2.16. The error messages being ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

Creating a dynamic progress bar with jQuery that randomly adjusts the width of an

I'm struggling to figure out what I'm doing incorrectly. My goal is to set the width of an image to a random value between 0 and 100%. Can someone help me identify my mistake? function updateProgressBar() { $("body").append("<div class=& ...

What is the Method for Installing and Accessing a Database After Installing a Chrome Extension?

Currently, I am developing a Chrome extension which requires the storage of data in a local database without directly accessing it. Given my limited experience with Chrome extensions and their limitations, I am unsure about how to go about downloading t ...

Having trouble uploading a Nodejs application to Heroku due to a missing bower component

Despite searching through various stackoverflow posts, I haven't found a solution that works for me. Trying to deploy my NodeJS app on Heroku keeps resulting in an error message related to bower. Manually adding bower in my dependencies or transferrin ...

What is the recommended contentType to designate when responding with a JSON object?

When making an AJAX call, I am not sending any data but fetching them in response which was previously set by another request. On the server side, I am building a jsonObject and sending it; what contentType should I use: application/x-json or text/x-json ...