The most effective method for transforming an array into an object in JavaScript using a prefixed value as the key

I am working with an array that contains prefix values

["options_a",
"options_b",
"options_c",
"capable_d",
"capable_e_c"
]

I am looking for a way to transform this array into an object format with the prefix as the key and the grouped split string as the value

The desired output format is:
{
"options":["a","b","c"],
"capable":["d","e_c"]
}

I understand that this can be achieved with a normal for loop, but I am wondering if there is a more simplified way using ES6 functionality.

Any suggestions would be greatly appreciated.

Answer №1

Shorten the array of values starting with a prefix. Separate each item by an underscore (_), then use destructuring to extract the key and an array of values (which may include multiple items after the split). If the accumulator (acc) does not have the key, create a new one with an empty array. Add the value to acc[key] after combining it with underscores.

const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"]

const result = arr.reduce((acc, item) => {
  const [key, ...value] = item.split('_')
  
  if(!acc[key]) acc[key] = []
  
  acc[key].push(value.join('_'))

  return acc;
}, {})

console.log(result)

To eliminate the need for joining, use a RegExp to split only at the first underscore (refer to this answer):

const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"]

const result = arr.reduce((acc, item) => {
  const [key, value] = item.split(/_(.+)/)
  
  if(!acc[key]) acc[key] = []
  
  acc[key].push(value)

  return acc;
}, {})

console.log(result)

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

Exploring the capabilities of Three.js Projector and Ray components

Recently, I've been experimenting with the Projector and Ray classes for collision detection demos. My main focus has been on using the mouse to interact with objects by selecting or dragging them. While studying examples that utilize these classes, I ...

using javascript to animate multiple div elements

In my current project, I am harnessing the power of Javascript to incorporate some eye-catching animation effects on a rectangle. Once the animation is complete, I have set the box to disappear from view. Check out the code snippet below for more details: ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

The API response was blocked due to the CORS header "Access-control-allow-origin."

I have an index.html file that is used for making HTML and Ajax calls. When I run the file through localhost, the API works perfectly. However, if I directly open the index.html file in Google Chrome or Mozilla Firefox, I encounter a CORS (Cross-Origin Re ...

Combining Arrays in MATLAB by Matching Specific Columns

After obtaining a NetCDF file containing variables such as day (in julian), latitude, longitude, and ozone, I successfully converted the file into a 3D matrix ordered by longitude, latitude, and day. In addition, I possess a .mat file that includes Year, ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

Using JQuery, you can toggle a newly created DIV element by linking it to `$(this)` instead of `$(this).closest()`

In the comment section, there is a link called "Reply" that triggers a pop-up comment box when clicked. However, I want the comment box to disappear if the "reply" button is clicked again, as it currently keeps opening more comment boxes. $('.replyli ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

Vue Bootstrap Checkbox and <b-table> with <b-form-checkbox> components combine to provide a powerful and flexible user

I am currently implementing b-form-checkbox with b-table to fetch the selected module Ids. <b-table id="module-table" :items="list.modules" :fields="fields" :busy="isBusy"> <template slo ...

What is the best way to merge arrays from various ObservableObjects using combine?

In developing my app, I encountered a challenge with managing tags for tasks and notes. Both task and note objects can have an array of tags, which are stored in separate TaskStore and NoteStore classes. When users edit a task or note, they interact with T ...

Utilize JSON or an environment file to pass dynamic values to an npm script

I've been working on setting up an npm script for deploying react apps (specifically using create-react-app). However, I'm facing a challenge in setting the S3 bucket url string in either an environment variable or JSON file. This way, I can easi ...

Does Three.js lighting adjust according to the bundler used?

Today, I decided to streamline my portfolio project by transitioning it from standard HTML to the Vite bundler for easier dependency management. I simply copied and pasted the existing code, making adjustments to the imports since I had been using relative ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

The issue with onclientclick in Asp.Net button

I am experiencing a peculiar problem that I cannot seem to solve. The issue revolves around a button that I have implemented using the following code: <asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save" OnClientClick="return Confi ...

How can a HTML element be clicked in JQuery to copy it into a text area?

Is it possible to select text from a list and insert it into a text box by clicking on it? I have developed a JSON API that retrieves a list of individuals from the database. Following this, there is a form with a text field that displays the list of peopl ...

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

Retrieving CSV information from several files within a JavaScript directory

Currently, I am attempting to retrieve data from numerous CSV files using 'csvtojson'. Firstly, I gathered an array of file names in a specific directory. Then, I used a forEach loop to extract data from various CSV files and convert it to JSON ...

Using React client to accept messages from a Socket.io server: A guide

I have a setup where a Node.js server with Socket.io is used to send messages between React clients. Currently, I can send a message from Client 1 to Client 2, but the recipient must click a button to view the message on their screen. I am trying to make i ...

The variable 'props' is given a value but is never utilized - warning about unused variables in Vue 3

Within my Vue component file, I am using the following code: <template> <router-link :to="{ name: routerName }" type="is-primary" class="inline-flex justify-center py-2 px-3 mb-3 border border-transparent shado ...