Tips for categorizing items based on their names

Upon receiving a response as shown below:

   [
     {id:1,name:"type1-something"},
     {id:2,name:"something-type2"},
     {id:3,name:"type3-something"},
     {id:4,name:"something-type1"}
   ]

I have an Enum with all the names from the response stored in it:

enum E{
  E1 = 'type1-something',
  E2 = 'something-type2',
  E3 = 'type3-something',
  E4 = 'something-type1',
}

The task at hand is to group the response based on their names. For instance, the transformed output should look like this:

{
 "Type1" : [{id:1,name:"type1-something"},{id:4,name:"something-type1"}],
 "Type2" : [{id:2,name:"something-type2"}],
 "Type3" : [{id:3,name:"type3-something"}],
}

What would be the best approach for this? One idea could be using a map along with a for loop:

if (object.name == E1 || object.name == E4)
   MAP['Type1'].push(object)

However, with over 30 entries in the enum, this solution might become convoluted and hard to manage. While incorporating smaller enums could reduce the code complexity, I am curious if there exists a simpler solution that I may not have considered.

Answer №1

If you need to determine the type and group based on a specific value, you can utilize this method.

const
    getDetails = ({ description }) => description
        .match(/category\d+/g)
        ?.map(s => s[0].toUpperCase() + s.slice(1))
        .join('-') || '',
    items = [{ id: 1, description: "category1-something" }, { id: 2, description: "something-category2" }, { id: 3, description: "category3-something" }, { id: 4, description: "something-category1" }, { id: 5, description: "category3-category1-something" }],
    dataResult = items.reduce((resultObj, item) => {
        (resultObj[getDetails(item)] ??= []).push(item);
        return resultObj;
    }, {});

console.log(dataResult);
.output-console { 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

Why is this tetris piece not appearing fully on the grid when using arrays?

Below is the code snippet, and you can find a link to the jsfiddle below. I'm facing an issue where the first row of the block is not being drawn, and dealing with these 2-dimensional loops is quite challenging for me. I am unable to figure out why t ...

One way to determine whether .ajax is using Get or POST is to check the type parameter

I have a query: $.ajax({ url: "http://twitter.com/status/user_timeline/treason.json?count=10&callback=?", success: function (data, textStatus, jqXHR) { }, error: function (jqXHR, textStatus, errorThrown ...

What is the most effective method for implementing grid-based scrolling in a top-down RPG game?

In my browser-based application, which is currently built using PHP, JavaScript, HTML5, and jQuery as the only framework, I have a question regarding image scrolling. If I have enough 64x64 images to fill up my screen about 100 times, what technique would ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html. The code snippet I have been using looks something like this: <tbody v-i ...

JavaScript comparing variables to nested object properties

items resembling this are heading my direction: var info = { a0: { name: 'lengthy title 0', var1_min: '10', var1_max: '99', select: ['alpha', 'gamma'], display: 'value0' }, b12: { ...

Guide on how to execute an API request prior to rendering a component in React JS

export default function Dashboard(){ useEffect(() => { setTimeout(()=>console.log("API Call Completed"),5000) },[]) return( <div> <h1>Dashboard</h1> </div> ...

A step-by-step guide on incorporating universal CSRF tokens using JQuery AJAX

As part of my development work, I am in the process of creating jquery code that communicates with the server through ajax to input data into a database based on specific request parameters. My main concern at this point is the vulnerability to CSRF attac ...

Utilizing object as props in ReactJS with TypeScript

I'm new to working with ReactJS, and I made the decision to use typescript for my current project. The project is an application that fetches movies from an API and displays them. Take a look at the app: import React from 'react'; import &a ...

How can I iterate through multiple rows in JavaScript?

Feeling stuck, the simple yet dreaded for loop has become my nemesis and I could really use some guidance. Currently, I have a Google sheet with 3 rows (excluding headers) and 8 columns. As users input data via a web app, the number of rows will dynamicall ...

How do I dynamically adjust class names for menu items as I scroll using jQuery?

I have a website with different sections identified by unique IDs, such as: <section id="home"> First Section </section> <section id="about_us"> Second Section </section> <section id="what_we_do&q ...

What is the best way to validate the body object when working with Actions2 in sails.js?

Just starting out with sails.js I understand that the inputs object allows actions2 to validate the request parameters. However, how can I access and validate the request body? For example, req.body. I know I can access this from this.req.body, but I was ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Guide to positioning the highlighted image in a lightbox gallery: Aligning the active image in the

Hey there, I have implemented the Lightbox gallery feature in my Django application. The gallery functions such that when a user clicks on an image, it opens up the gallery with the selected image displayed prominently, along with the functional icons for ...

Unable to verify password against NodeJS hash Passport

I am working on creating a function that will allow users to change their password. The first step is to compare the old password with the user's current password in the database. I have written code for this inside the router function, but it doesn&a ...

Is a missing dependency causing an issue with the React Hook useEffect?

I've encountered an issue with the following code snippet, which seems to only depend on [page]. Despite this, I am receiving the error message: React Hook useEffect has a missing dependency I've come across similar discussions suggesting to com ...

Laravel error 500 (Internal Server Error) is encountered when making an ajax post request

I've already added the csrf token to my view and I'm still getting an error. I've searched everywhere for a solution, but all I find is to add the csrf token, which I've already done. What should I do next? <meta name="_token" conte ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

Utilizing information shared between parent and child classes to plot points on a globe

Working on an exciting project to enhance my ReactJS and ThreeJS knowledge, I encountered an issue with passing data from the parent class to functions in the child class. Here's a glimpse of my project: App.js import React, {Component} from 'rea ...