Proficient in transforming arrays into objects

Having difficulty with a particular javascript problem. Is there a way to approach it in this manner?

// Given the input data, I aim to produce output as shown below
const ListValues = ["id", "name", "description"]

// Expected output
const initialValues = {
    id: "",
    name: "",
    description: "",
}; 

Appreciate any assistance. Have a fantastic day <3

Answer №1

To create your desired object from the input, you have the option to utilize Object.fromEntries() and Array.map().

const ValuesList = ["id", "name", "description"];

const initialData = Object.fromEntries(ValuesList.map(value => [value, '']));

console.log('initialData:', initialData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you prefer, you can achieve the same outcome by employing Array.reduce():

const ValuesList = ["id", "name", "description"];

const initialData = ValuesList.reduce((accumulator, current) => {
    accumulator[current] = '';
    return accumulator;
}, {});

console.log('initialData:', initialData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

New parents, same name D3.JS

Currently utilizing d3.js to visualize a tree structure. When parsing the JSON object containing nameOfNode and NameOfParent, encountering an issue when there are two nodes with the same name. Seeking recommendations on the most effective way to address ...

Error message: The md-autocomplete function is throwing a TypeError because it cannot read the property 'then' of an undefined object

I am encountering an issue with the md-autocomplete component from angular material. Here is my code snippet: <md-autocomplete required md-search-text="searchTxt" md-selected-item-change="setModelValue(item.name)&q ...

`Hovering over a div triggers a continuous animation loop`

I've gone through various questions and solutions related to this issue, but unfortunately, none of them seem to work for me. It's possible that I might be overlooking something or my scenario is slightly unique. The main problem I'm facing ...

Is there a way to automatically change the full screen background on refresh?

Is there a way to have the background image of this website change to different pictures every time the page is refreshed? I'm curious about how this can be achieved. I noticed that Offliberty is able to do this. I tried looking at the source code b ...

Sending data from JavaScript to Jade templatesIs this alright?

Utilizing node.js, express, jade, and socket.io, I have successfully executed JavaScript code on the jade side. However, I am encountering difficulty in generating HTML output from the script block. Based on your feedback, I have updated my question to in ...

What is the best way to store chat messages in a React application?

My idea for a chat application using React involves saving chat messages in localStorage. Below is the code snippet that illustrates this functionality: const [textMessages, setTextMessages] = useState([]); const [textValue, setTextValue] = useState(' ...

What is the best way to extract data using Angular from the backend and then transfer it to the frontend using Node.js?

Recently, I decided to make a change in my node.js application. Previously, I was using the EJS template engine but now I want to switch to Angular. To do this, I have already installed Angular and it is working well. However, I am facing an issue while t ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

Tips for sending data from a JSP to a Servlet with Javascript

My code creates an array of circular buttons with dynamic values. When clicked, these buttons get deleted and their values are stored in a JavaScript object array. I need to send these deleted button values to a servlet once my task is complete. To do this ...

Display the file name of the following/preceding images on the backward/forward button

Hello, I am fairly new to web development and could use some professional assistance. I have a slideshow set up, but I am struggling with adding the filename of the next or previous images to the back/forward icons of the slideshow. Is this achievable with ...

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

Code: Ensuring URL spaces are maintained

In my Angular 4 project, I have a service with a delete API that requires two strings as parameters. Here is an example of how it looks: this.http.delete(this.url + 'api/v1/ReportingService/collectionID/'+ '45902' +'/'+' ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Creating a Nested Array within a JSON Object in PHP

In order to achieve the desired format output of the JSON Object, I am implementing the following steps: [ { "id":1, "title":"Test Title", "url":"http://test.com/", "images":[ { "width":100, ...

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...

Alert: '[Vue warning]: Directive "in testing" could not be resolved.'

Currently, I am running unit tests within a Vue 2.0 application using PhantomJS, Karma, Mocha and Chai. Although the tests are passing successfully, I am encountering a warning message with each test indicating an issue like this: ERROR: '[Vue warn ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

Add each individual item from the array into the database sequentially

I have a collection of data entries that I need to individually insert into the database, like so: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] In essence, I plan to use a for..of loop to iterate over this array and add them one by one. If ...

The step-by-step guide on displaying API choices in an Autocomplete feature and keeping them up

Having trouble with updating autocomplete options. An error message pops up in the console log when I try to deselect a tag or select a new one: MUI: The value provided to Autocomplete is invalid. None of the options match with [{"catName":{&qu ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...