How can I enhance this conversion function from an Array to an Object in JavaScript?

Looking to construct an object consisting of empty arrays using values as keys.

const CATEGORIES = ['apple', 'banana', 'orange']
generateCategoryObject() === { apple: [], banana: [], orange: []}
function generateCategoryObject() {
    const categoryObj = {}

    for (const fruit of CATEGORIES) {
        categoryObj[fruit] = [];
    }

    return categoryObj;
}

Hoping to enhance my understanding of ES6. Any suggestions on a concise solution for this?

Answer №1

Using FILTERS.reduce((x,y) => Object.assign(x, { [y]: []}), {})

Answer №2

If you want to try out a different approach, consider utilizing the modern Object.fromEntries() method. Nonetheless, always verify the browser compatibility before implementation. Here's an example where Object.fromEntries() is combined with Array.map():

const FILTERS = ['foo', 'bar', 'baz'];

let res = Object.fromEntries(FILTERS.map(x => [x, []]));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №3

If you're comfortable with post-ES6, you can utilize Object.fromEntries:

Object.fromEntries(FILTER.map(keyword => [keyword, []]))

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

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Is it possible to utilize Vue.js' v-if directive to validate if a certain value is present within an array

In my form, I have a checkbox and I want to be able to use v-if directly to display or hide sections based on the selected checkbox values. Can this be done using v-if, or do I need to use watch:? ...

The ng-repeat function is failing to show any data on the HTML view, instead only displaying a row for each property present

HTML Code: <div ng-repeat="addr in addrShipData"> <input type="radio" name="resp1" ng-checked='true'/> {{addr.addressLine1 +","+addr.addressLine2+", "+addr.city+ ","+addr.state+", "+addr.country+", "+addr.zipCode+","+addr ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

Ajax-powered Datatables

I am a beginner to data tables and I am attempting to retrieve data from a JSON text file (test1.txt). Below is an excerpt of the data present in the file, which contains over 5000 entries: [{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"2212630 ...

The model.find operation is failing to retrieve the necessary fields from the database

When I execute console.log(correct.password), it returns undefined, even though the if condition results in false. app.post('/login' , async (req , res)=> { const correct = data.findOne({name : req.body.name}).select({name : 0}); if(!c ...

Deactivate the underscore and include the fiscal year in AngularJS

I am currently faced with a scenario where the back end is returning the value as follows: 123222_D1.123 However, I need to display the date from the database (12-Jun-2020) as 2020-D1.123 in a drop-down menu. Currently, I am displaying the above value i ...

HTML5 Drag and Drop: How to Stop Drag and Drop Actions from Occurring Between a Browser and Browser Windows

Is it possible to restrict HTML5 Drag & Drop functionality between different browsers or windows? I am currently working on an Angular2 app that utilizes native HTML5 Drag and Drop feature. Is there a way to prevent users from dragging items out of th ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

What steps should I take to successfully install using npm if I keep encountering the same error?

Every time I attempt to install a package using npm, I encounter the following warning: npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b3aeaba2b3be ...

Utilizing Django models to populate Google Charts with data

I am currently working on showcasing charts that display the most popular items in our store. To achieve this, I need to extract data from the database and incorporate it into the HTML. Unfortunately, the charts are not loading as expected. When testing wi ...

Error: Authentication Error - Headers have already been sent to the client and cannot be modified

I am currently working on handling authentication errors for my website. However, when I submit incorrect data, I encounter the following error: node:internal/errors:478 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers aft ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

React component making an Axios request only receives the initial state as a response

I'm struggling with creating an AJAX call using Axios in React. Despite my efforts, I can't seem to pinpoint where the issue lies. Below is what I currently have within my component: ComponentDidMount() { axios.get('https://jsonplacehol ...

What other ways can websockets be utilized besides comet?

Websockets offer a more efficient solution for comet (reverse Ajax, often achieved through long-polling). However, are there other ways we can utilize websockets? For instance: - Can websockets be used to facilitate communication between different bro ...

Tips for ensuring the HTML checkbox element is fully loaded before programmatically selecting it

When a user accesses the page, I want certain checkboxes to be automatically checked. To achieve this, I am storing the IDs of the HTML checkbox elements in a service. Upon entering the page, the service is utilized to retrieve an array containing these ID ...