Combining several objects into a single one in TypeScript while handling duplicate keys

I'm currently using ng2-charts and I'm looking to create a horizontal bar chart. The values are obtained within a keys.forEach loop, resulting in the console.log output for my data as follows:

{ReasonA: 5}
{ReasonA: 5, ReasonB: 5}
{ReasonA: 1, ReasonB: 3, ReasonC: 2}
{ReasonA: 1, ReasonB: 4, ReasonE: 2}

My goal is to merge these objects into one, consolidating multiple values under the same key. The expected outcome in this scenario would be:

{ReasonA: 12, ReasonB: 12, ReasonC: 2, ReasonE: 2}

Having achieved this merged object, I can then separate the keys and values to populate the chart. Could you provide guidance on how to combine the 4 objects into the desired result?

Thank you in advance.

Answer №1

When dealing with properties that are all numbers, the process becomes straightforward by utilizing an array and the reduce method. However, if the properties consist of different types, the logic required becomes a bit more intricate. Below is a sample function that can be used to accomplish this task:

function addProperties(...objects: { [key: string]: number }[]) {
  return objects.reduce((acc, obj) => {
    for (let key in obj) {
      let currentTotal = acc[key] || 0;
      let valueToAdd = obj[key];
      acc[key] = currentTotal + valueToAdd;
    }

    return acc;
  }, {});
}

Example Usage:

addProperties(
  {ReasonA: 5},
  {ReasonA: 5, ReasonB: 5},
  {ReasonA: 1, ReasonB: 3, ReasonC: 2},
  {ReasonA: 1, ReasonB: 4, ReasonE: 2},
)

Answer №2

Another way to achieve this is by utilizing the forEach method along with Object.keys to iterate over each object key and checking if it exists in the result object. If it does, then the value is incremented, otherwise a new value is assigned.

const mergeObjects = (...objects) => {
  const result = {};
  objects.forEach(obj => Object.keys(obj).forEach(k => result[k] ? result[k] += obj[k] : result[k] = obj[k]));
  return result;
}

console.log(mergeObjects(
  {ReasonA: 5},
  {ReasonA: 5, ReasonB: 5},
  {ReasonA: 1, ReasonB: 3, ReasonC: 2},
  {ReasonA: 1, ReasonB: 4, ReasonE: 2}
));

Answer №3

By utilizing lodash's _.extendWith, you can significantly reduce the amount of code needed for the task at hand :)

_.extendWith({FeatureX: 8},
             {FeatureX: 8, FeatureY: 6},
             {FeatureX: 2, FeatureY: 4, FeatureZ: 1},
             {FeatureX: 3, FeatureY: 5, FeatureW: 2}, 
             (obj, src) => (obj||0) + (src||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

Creating unique custom 404 error pages for specific sub-directories within NextJS using the App Router Structure

Having trouble with my custom 404 error page (= not-found.tsx) files. I have two of them, one within app/(paths) and another within app/(paths)/(jobs)/jobs/(cats). The issue is that the first not-found file should render when a user visits url example myap ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

What is the best way to access a value from a settings.json file in an Angular .ts file?

I am working on implementing debounceTime to allow the user to finish typing before suggestions are generated. I want to give the user the ability to customize how much time is given before suggestions appear. To achieve this, I have added a configuration ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

Sending Information to Child Component in Angular2

Hi there, I'm currently facing an issue with passing data from a parent Component to a child component controller. Here is the markup code of my parent Component parent.component.html <element [mydata]="Value"></element> By using this ...

Incorporating TypeScript into a React-Native Expo development venture

While attempting to integrate TypeScript into a React-Native Expo project, I encountered an error when renaming a file from abc.js to abc.tsx: I have been following the instructions provided at: https://facebook.github.io/react-native/blog/2018/05/07/u ...

Unveiling the method of retrieving a targeted value from JWT in React

I'm struggling to retrieve a specific value from my JWT token in React. I am using the react-jwt library to decode the token, and when I log it, I receive this output: Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 ...

Is there a clever method to transform the property names of child objects into an array of strings?

I have a similar object that looks like this: { "name":"sdfsd", "id":1, "groups":[ { "name":"name1", "id":1, "subGroups":[..] }, { "name":"name2", "id":21, ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Tips for accessing properties in JSON objects using AngularJS

In my Angular project, I have a TypeScript class called CheckoutInfo. export class CheckoutInfo { lines: CheckoutInfoLine[]; taxRate: number; get subTotal(): number { return this.lines.reduce((acc: number, cur: CheckoutInfoLine) => ...

Methods for adding a new object to an array in Angular: Explained

How can I insert a new object in Angular? Here is the current data: data = [ { title: 'Book1' }, { title: 'Book2' }, { title: 'Book3' }, { title: 'Book4' } ] I would like to update the obje ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

What is the process for importing a local widget file in Angular?

I have a unique widget named employee-widget stored in the Angular application folder as employee-widget.js. Despite following the calling method below, the widget fails to load. Method 1: <div> <h4>Attempting to load the employee widget& ...

Creating new routes and lazy-loading in Angular CLI page generator

I have questions regarding the process of page generation and route creation by the CLI. When a new page is generated using the ng CLI, it creates the page module, HTML, spec, and SCSS files, as well as updates the routing module. 1) By default, the page ...

Angular project encountering issues in production mode despite setting base-href

My issue may be too broad for StackOverflow, as I don't have specific code to provide. This is a generic problem that I am hoping someone can help me troubleshoot. I've discovered that a base-href is necessary to specify the project's route ...

Launching Node Application

While working with NestJS and IIS, I encountered an issue when deploying my 'dist' folder on the server using IISNode. The error message 'module not found @nestjs/core' prompted me to install the entire 'package.json' files (n ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Why is it advantageous to use Observable as the type for Angular 5 component variables?

Being a beginner in Angular 6, I have been exploring the process of http mentioned in this link: https://angular.io/tutorial/toh-pt6#create-herosearchcomponent One thing that caught my attention was that the heroes array type is set to Observable in the ...