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

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

What could be causing the asynchronous function to return a pending promise even after using the await keyword?

I seem to be overlooking something as I cannot comprehend why my promise does not resolve. I have simplified the code to this basic example: ... console.log("before"); const promise = second(); console.log("after"); console.l ...

obtaining the data stored in the backing bean and showcasing it upon submitting the form

I currently have an a4j:commandbutton implemented on my jsf page. Here is the code snippet- <a4j:commandButton id="submitBtn" value="#{msgsMass.MM_04_02_BTN_CONTINUE}" reRender="addNewCardForm,saveAddNewCardForm" immediate="true" action="#{bBea ...

Can I create a unique initial command for my Azure Node.js web app using ES2015 and Babel?

I need to transfer an ES2015 node.js application from Heroku to Azure hosting. Currently, the start-up command on Heroku is "start": "./node_modules/babel-cli/bin/babel-node.js index.js" However, I encountered this issue while trying to replicate it on ...

What are the steps for implementing webpack 5 configurations in Next.js?

I can't seem to figure out how to properly add experiments to my webpack config. Here is my current environment: [email protected] [email protected] To set up, I started a new Next.js app using the command npx create-next-app blog Accord ...

Distinguish between datalist selection and text input in BootstrapVue Autocomplete

When looking at the code snippet provided below, I'm trying to figure out the appropriate event/method to determine whether the value entered in the input field was manually typed or selected from the <datalist>. SAMPLE CODE: <div> &l ...

Avoiding HTML (JSX) tag duplication in React Component

Having the same code in my React component multiple times is becoming repetitive and inefficient. Is there a way to follow the DRY principle and avoid repeating this code? While creating a landing page with Sass styling, I noticed that I am duplicating t ...

Arranging search findings based on relevance using javascript

I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

Using React's useState hook with an array of objects

When I have 3 different inputs, my goal is to capture their states while updating the onChange input attribute. The desired state format should be structured as follows: [{lang: (inputName), text: (inputValue)}, ..]. This is what I attempted: function onC ...

Challenges faced with dividing a string in JavaScript

Having trouble splitting a string in JavaScript, I can't seem to make it work. This is the JavaScript code I am using: var str = 'TestApplication20 Application200'; var parts = str.match(/(\d+)(\D.+)/).slice(1); var id = parts[0 ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

Troubleshooting: Jquery UI Draggable - Cursor losing track of draggable element

I want to create a draggable popup with Jquery UI functionality, but I'm facing an issue where the cursor does not stay aligned with the popup element when dragged. When dragging the popup element to the left, the mouse cursor goes beyond the div elem ...

How come my fixed navigation bar is appearing above my sticky navigation bar even though I positioned it at the bottom in the code?

My current project involves creating a sticky bar and fixed navbar using Bootstrap 5. I structured my code with one file for the sticky navbar and another file for the fixed navbar. The challenge I faced was having the fixed navbar overlap the sticky navba ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Tips for updating process.version in a Node.js environment

After upgrading my node version from v3 to v11 using nvm with the command nvm use 11.12.0, I noticed that when I check the version using node -v in the terminal, it correctly shows 11.12.0. I also have a node js application that is started through pm2. I ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...