A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript?

Consider the two Records below:

var dictionary1 : Record<string, string []> ={
    'fruits' : ['apple','banana', 'cherry'],
    'vegetables' : ['cucumber','onion']
};

var dictionary2 : Record<string, string []> ={
    'fruits' : ['apple','banana', 'orange', 'pear'],
    'vegetables' : ['cucumber','corn'],
    'beverages' : ['soda']
};

I want to merge these two Records to achieve the following combined result:

var mergedDictionary : Record<string, string []> ={
    'fruits' : ['apple','banana', 'cherry', 'orange', 'pear'],
    'vegetables' : ['cucumber','onion', 'corn'],
    'beverages' : ['soda']
};

Answer №1

Here is a possible solution - I have not yet tested it for performance

Check it out on typescriptlang.org/play

const dict1 : Record<string, string []> ={
    'fruits' : ['apple','banana', 'cherry'],
    'vegetables' : ['cucumber','onion'],
    'meats': ['beef']
};

const dict2 : Record<string, string []> ={
    'fruits' : ['apple','banana', 'orange', 'pear'],
    'vegetables' : ['cucumber','corn'],
    'beverages' : ['soda']
};

const mergedDict: Record<string, string []> = [dict1, dict2]
.reduce((acc, dic) => {
    const updated = Object.keys(dic).reduce((agg, key) => { return { ...agg, [key]: [...new Set([...(agg[key] || []), ...dic[key]])]}; }, acc);
    return { ...acc, ...updated };
}, {} as Record<string, string[]>);

console.log({ mergedDict });
  • The first reduce function combines the keys of the dictionaries
  • For each key, the content of the arrays needs to be combined
  • The second reduce merges the arrays for each key
  • If the key does not exist in the source map, we use a hack (agg[key] || []) to return an empty array
  • To avoid duplicates, a set is used and then converted back into an array
    [...new Set(/* merged arrays */)]

And here is the final result:

{
  "mergedDict": {
    "fruits": [
      "apple",
      "banana",
      "cherry",
      "orange",
      "pear"
    ],
    "vegetables": [
      "cucumber",
      "onion",
      "corn"
    ],
    "meats": [
      "beef"
    ],
    "beverages": [
      "soda"
    ]
  }
} 

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

Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside ...

Unlocking the power of URL manipulation in Fastify using Node.js

I'm attempting to retrieve specific parts of the URL from a Fastify server. For instance, the URL looks like this: http://localhost:300/query_tile/10/544/336 Within the Fastify server, I need the values for z/x/y. I've attempted the following ...

A beginner's guide to efficiently indexing tables in AngularJS

Having Trouble with ng-repeat Indexing <tr ng-repeat="Ward in Wardresult "> <td>{{$index + 1}}</td> ...................... some column ....................... </tr> Although, the output ...

Having trouble uploading an image using the Cloudinary API in a Next.js project

I am currently working on a page meant for creating posts. Initially, the page was designed to handle multiple image uploads. However, I made some adjustments so that it can now accept only a single image upload. Unfortunately, after this modification, the ...

Safari displays the contents of JSON files instead of automatically downloading them

I am facing an issue with a JavaScript code that generates a link to download a JSON file. The link is structured like this: <a href="data:text/json;charset=utf-8,..." download="foo.json">download</a> While the link works perfectly in Chrome ...

Why isn't data coming through after sending ajax post requests?

Why am I unable to retrieve data after sending AJAX post requests? During the process of sending an AJAX post request, I use $('#fid1 input,select').attr('disabled','disbaled'); to disable form inputs and then, after a suc ...

I attempted to use the Stripe API, but it seems to be non

I seem to be encountering an issue with the stripe.customers.create. My goal is to create a new Stripe customer using the email address of the current user, and then update my user with the generated customer.id. Despite the fact that stripe.customers.cre ...

What is the best way to arrange an array or display it accurately?

Guys, here's a challenge for you: extract the values from this JSON data: [[name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category]] Check out my JavaScript code: $(function(){ $('i ...

Is it possible for me to save external CDN JavaScript files to my local system?

Normally, I would include scripts from other providers in my application like this: <script src="https://apis.google.com/js/api.js"></script> However, I am considering whether it is feasible to simply open the URL , and then copy and paste th ...

What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem. "A task for you: Calculate the average score of a class whose test scores have been graded by a teacher. Your mission is to complete the getAverage function, which receives an array of test sco ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...

Upgrade jQuery visibility and opacity animations to pure JavaScript for a more lightweight solution

Currently I am in the process of removing jQuery from an older website. However, I have encountered a problem with an animation that is currently being used. I have managed to replicate the opacity fade effect, but I am struggling to smoothly transition t ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Ways to position divs without causing them to collapse or override existing divs

I am currently developing a demonstration in which users can select jQuery areas to create square blocks. When a user selects an area and adds a comment with color, the entire block is displayed at a specific position. This feature is working perfectly as ...

Exploring JSON data in AngularJS

After creating a new Angular App, I decided to store some data in a JSON file. My main concerns are where to best store the .json file within the app and how to access it. Currently, I am facing this error in my Chrome console: GET http://localhost:8000/t ...

How should one approach working with libraries that do not have type definitions in TypeScript?

My current situation involves working with libraries that are untyped and resulting in warnings. I am curious about the best approach to address this issue - should I adjust configurations, use tslint ignore on a line-by-line basis, or possibly create du ...

utilizing the angularjs $scope variable within a jquery bind method

I recently implemented the Fullcalender directive in my AngularJS application. While I was going through the documentation, I noticed that there is a double click handler available in the Fullcalender jQuery plugin. For reference: http://code.google.com/p ...

Is there a way to identify the index of user input when using the .map method?

I'm currently utilizing the Array.prototype.map() method to present an array within a table. Each row in this table includes both an input field and a submit button that corresponds to each element from the Array.prototype.map() function. Is there a w ...