What is the process of transforming an array of strings into a key-value pair object, where the value is an array?

My array contains strings as shown below:

[
    "hl7_file_type_1.msgtype",
    "hl7_file_type_1.filename",
    "hl7_file_type_2.msgtype",
    "hl7_file_type_2.filename",
    "hl7_file_type_3.msgtype",
    "hl7_file_type_3.filename"
]

I aim to transform this into a key-value pair object like this (expected result):

{
"hl7_file_type_1": ["msgtype","filename"],
"hl7_file_type_2": ["msgtype","filename"],
"hl7_file_type_3": ["msgtype","filename"],
}

This is my current approach:

let tmp = {};
for (let i = 0; i < this.regexArray.length; i++){
      let split = this.regexArray[i].split('.');
      tmp[split[0].trim()] = split[1].trim();
    }
    console.log('Key Value')
    console.log(tmp);

However, it currently returns:

{
    "hl7_file_type_1": "filename",
    "hl7_file_type_2": "filename",
    "hl7_file_type_3": "filename"
}

How can I modify my function to produce the expected result outlined above?

Answer №1

To accomplish this task, you can utilize the power of reduce method

const data = [
  "hl7_file_type_1.msgtype",
  "hl7_file_type_1.filename",
  "hl7_file_type_2.msgtype",
  "hl7_file_type_2.filename",
  "hl7_file_type_3.msgtype",
  "hl7_file_type_3.filename",
];

const output = data.reduce((accumulator, current) => {
  const [property, value] = current.split(".");
  if (!accumulator[property]) accumulator[property] = [value];
  else accumulator[property].push(value);

  return accumulator;
}, {});

console.log(output);

Answer №2

To solve this problem, a combination of mapping and reducing is necessary

const input = [
    "hl7_file_type_1.msgtype",
    "hl7_file_type_1.filename",
    "hl7_file_type_2.msgtype",
    "hl7_file_type_2.filename",
    "hl7_file_type_3.msgtype",
    "hl7_file_type_3.filename"
]

const result = input.map(i => i.split(".")).reduce( (acc,[key,value]) => {
  return {
    ...acc,
    [key]: [...(acc[key] || []), value]
  }
},{});

console.log(result);

Answer №3

To simplify, you can use the map method followed by the reduce method.

const data = [
  "hl7_file_type_1.msgtype",
  "hl7_file_type_1.filename",
  "hl7_file_type_2.msgtype",
  "hl7_file_type_2.filename",
  "hl7_file_type_3.msgtype",
  "hl7_file_type_3.filename",
];

const res = data
  .map((d) => d.split("."))
  .reduce((r, [k, v]) => ((r[k] ??= []), r[k].push(v), r), {});

console.log(res);

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

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...

What is the best way to incorporate a listener into an Angular directive?

I have a custom directive that generates a dynamic Google chart. My goal is to activate an event handler on the controller's scope whenever the directive detects an event from the chart. For example: http://plnkr.co/edit/yn4KuQfrYvlQNbPSWk3Q?p=previe ...

Navigating files using NodeJS and ExpressJS

Can NodeJS (or ExpressJS) facilitate the following task? Although I appreciate the flexibility that routing provides, I find the configuration process quite cumbersome. (I don't consider myself an expert in Express) For instance, imagine an applicat ...

Are there restrictions on the amount of Client-Side requests allowed for the Google Custom Search API?

My Google Developers account states that the limit is set at 1,000 requests per day for a specific API key. My question is whether this limit applies to the server or the client side. I am currently using the deprecated API for making AJAX requests on the ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

Implementing authentication middleware with React Router in a React component

Working on my app.js, I'm trying to implement an Auth component that acts as middleware to check if the user is logged in. const App = props => ( <BrowserRouter> <Provider store={store}> <div className="app"& ...

Endless cycle encountered when executing grunt-concurrent with 'nodemon' and 'watch' operations

Currently, I'm experimenting with the grunt-concurrent task in order to utilize grunt-nodemon for watching my JS scripts. This setup allows me to concurrently use watch to continue executing concat and uglify on my files whenever they change. Upon ru ...

Unable to recycle SASS @mixin: Repeating previous parameter value

I am attempting to give 3 circle icons a glowing effect using a Sass @mixin with Font Awesome icons. _mixins.scss @mixin textGlow($glowColor: 0){ @keyframes glow{ from { text-shadow: 0 0 1px $glowColor, 0 0 2px $glowColor, 0 0 3px ...

What is the importance of having an index.js file, even when the main entry point in package.json is changed to app.js?

I recently made a modification in my react application by switching the main entry point from index.js to app.js. However, I noticed that if I do not import app.js into my index.js, the program crashes. Does anyone have any insight into why this may be h ...

What is the best way to enhance my mapbox-gl map in an angular application by utilizing a forEach loop?

I am looking to enhance my map by incorporating multiple features into a single source, rather than just a single line. In my typescript code, I currently have an array called myRoutes that contains all the routes (coordinates for the lines to be drawn). ...

Creating a TypeScript type based on the static values of a class

In my Market class, there is only one parameter: name. class Market { name: string constructor(name: string) { this.name = name } } Next, I have a Markets class that contains a static collection of multiple markets. class Markets { static M1 ...

Require fields in TypeScript interfaces only for array types

Is there a way to make only array type interface fields required, not all of them? The Required operator currently makes every field mandatory, but I specifically need just the array fields to be required. ` interface IExample { a: number, b?: str ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...

Tips for executing multiple function calls within a single React component

Struggling to retrieve information from two separate API calls within the same React component. The issue seems to be with accessing the similar data in the code provided. function Info() { let params = useParams(); const [details, setDetails] = useSt ...

Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}> <div classname="div-1"></div> <div classname="div-2"></div> <div classname="div-3"></div> <div classname="div-4"></div> ...

What could be triggering the "slice is not defined" error in this TypeScript and Vue 3 application?

I have been developing a Single Page Application using Vue 3, TypeScript, and the The Movie Database (TMDB) API. In my src\components\MovieDetails.vue file, I have implemented the following: <template> <div class="row"> ...