Combining multiple arrays of objects using multiple keys with Angular 9 and Typescript

I have two JSON objects (displayed here with JSON.stringify(array of objects)) GPRows data is

[
   {
      "shopName":"Testing One",
      "state":"NSW",
      "yearMonth":"20203",
      "id":29,
      "shopId":1,
      "paintSale":80000,
      "panelSale":80000,
      "partsSale":80000,
      "otherSale":80000,
      "paintCost":80000,
      "panelCost":80000,
      "partsCost":80000,
      "otherCost":80000,
      "panelWages":80000,
      "paintWages":80000,
      "depreciation":80000,
      "forecastedSales":80000,
      "expenses":80001
   },
   {
      "shopName":"Not yours",
      "state":"SA",
      "yearMonth":"20204",
      "id":28,
      "shopId":2,
      "paintSale":85000,
      "panelSale":80000,
      "partsSale":80000,
      "otherSale":80000,
      "paintCost":80000,
      "panelCost":80000,
      "partsCost":80000,
      "otherCost":80000,
      "panelWages":80000,
      "paintWages":80000,
      "depreciation":80000,
      "forecastedSales":80000,
      "expenses":80000
   },
   {
      "shopName":"Testing One",
      "state":"NSW",
      "yearMonth":"20201",
      "id":31,
      "shopId":1,
      "paintSale":75000,
      "panelSale":75000,
      "partsSale":75000,
      "otherSale":75000,
      "paintCost":60000,
      "panelCost":42000,
      "partsCost":45000,
      "otherCost":20000,
      "panelWages":75000,
      "paintWages":75000,
      "depreciation":75000,
      "forecastedSales":75000,
      "expenses":75000
   }
]

and

BudgetTargets data is

[
   {
      "shopName":"Testing One",
      "state":"NSW",
      "yearMonth":"20202",
      "shopId":1,
      "sales":487500,
      "costs":80000,
      "expenses":90000,
      "netprofit":25000,
      "arc":2100,
      "numVehicles":232,
      "ppv":108,
      "wagesperc":10,
      "gPperc":40
   },
   {
      "shopName":"Not yours",
      "state":"SA",
      "yearMonth":"20204",
      "shopId":2,
      "sales":487500,
      "costs":80000,
      "expenses":90000,
      "netprofit":25000,
      "arc":2100,
      "numVehicles":232,
      "ppv":108,
      "wagesperc":10,
      "gPperc":40
   }
]

I am considering mapping them based on yearMonth and shopId or creating a function to query BudgetTargets value for specific entries in my Angular *ngFor loop of the GPRows array

Answer №1

Locate elements in the GPRows list that meet a specific condition in the BudgetTargets list, then combine them into a single object. If no matching element is found, return the original GPRows item.

const GPRows = [ { "shopName": "Testing One", "state": "NSW", "yearMonth": "20203", "id": 29, ... }, ... ];

const BudgetTargets = [ { "shopName": "Testing One", "state": "NSW", "yearMonth": "20203", ... }, ... ];

const dataMerged = GPRows.map(GPItem => {
    const budgetTargetItem = BudgetTargets.find(bTItem =>
        bTItem.yearMonth == GPItem.yearMonth && bTItem.shopId ==
        GPItem.shopId);
    return budgetTargetItem !== undefined ? {
        ...GPItem,
        ...budgetTargetItem
    } : GPItem
});

document.querySelector("#app").innerHTML =  "<pre>"+JSON.stringify(dataMerged,null, 2) +"</pre>";
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}
<div id="app"></div>

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

Incorporating AppLozic's chat plugin into an Angular 5 project

Struggling to incorporate a third-party chat plugin into my Angular 5 project. The documentation is proving difficult to understand, and I can't figure out how to proceed. If anyone has successfully integrated it before, your help would be greatly app ...

Iterating through the entire table presents a challenge when trying to display multiple values on a single element

I'm facing a challenge in dynamically adding data from an SQL Table to HTML. Here is my loop: @foreach (var item in Model.ModulesSubStages) { <div class="row"> <div class="col-md-6"><a id="courseRed ...

What sets a module apart from a script?

As I delve into the depths of TypeScript documentation to grasp the concept of modules, particularly ES6 modules, I stumbled upon some interesting insights. typescript-modules - this documentation talks about typescript modules and highlights an important ...

Issue with double-clicking in Selenium WebDriver using C#

I am attempting to perform a double click on an option within a selectbox using the Actions class in C# Selenium WebDriver. Although the code works perfectly in Firefox, it does not work as expected in IE or Chrome. Any advice on why this might be happenin ...

Read the file input using a StreamReader and display the content in label forms through a loop

My program is designed to allow the user to select a date using the DateTimePicker, with options ranging from January 1st, 2018 to January 31st, 2018. Upon selecting a date, the information stored in the imported text file (weather.txt) should be displayed ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Sending a model from a View to a boolean method using AJAX in ASP.NET MVC

I am looking to pass a model from BeginForm to a boolean method in the Controller. If the boolean method returns TRUE, I want to refresh a partial view using AJAX. Otherwise, if it returns FALSE, I want to display a pop-up with information from the method ...

Unusual TypeScript Syntax

While examining a TypeScript function designed to calculate average run time, I stumbled upon some unfamiliar syntax: func averageRuntimeInSeconds(runs []Run) float64 { var totalTime int var failedRuns int for _, run := range runs { ...

Is there a way to position the label to the left side of the gauge?

Is there a way to position the zero number outside the gauge? I'm having trouble figuring out how to do it because the x & y options won't work since the plotLine's position keeps changing. The zero needs to move along with the plotLine and ...

I am encountering an issue where my TSX import is being declared but not read when I attempt to pass it to the Jest render method. Can anyone explain

My Jest test file includes a simple import of a TSX component in my nextjs 13 project. However, when I try to use the component as a TSX tag, an error occurs: "'Properties' refers to a value, but is being used as a type here. Did you mean ...

Best practices for managing CSV files in Next.js with TypeScript

Hello, I am currently working on a web application using nextjs and typescript. One of the features I want to implement is a chart displaying data from a csv file. However, I am not sure if using a csv file is the best choice in the long run. I may end up ...

AmCharts issue in NextJS - Unusual SyntaxError: Unexpected token 'export' detected

Encountered an error while trying to utilize the '@amcharts/amcharts4/core' package and other amchart modules in a NextJS project: SyntaxError: Unexpected token 'export' After searching through various resources, I came across a helpf ...

Encountering a TypeScript error while calling a Vue lifecycle hook method

Struggling to call a method in a Vue root component from a lifecycle method in typescript? See below for a simple example that showcases this issue: import Vue from "vue"; class Game { a: number; b: number; constructor() { this.a = 3; ...

Transforming pictures from a word document to a bitmap entity

Our project requires us to convert images from a Word document into a bitmap object. In an attempt to achieve this, we have tried converting an InlineShape object from the Microsoft.Office.Interop.Word dll into a bitmap. Unfortunately, we have been unsucce ...

What is the process for adding custom text to create a .d.ts file using the TypeScript compiler?

In my endeavor to develop a javascript module using TypeScript that is compatible with ES5 browsers and NodeJs modules, I have encountered a dilemma. I wish to avoid using import and export in TypeScrtipt as it creates dependencies on SystemJS, RequireJS, ...

Responsive Container MUI containing a grid

I am attempting to replicate the functionality seen on YouTube's website, where they dynamically adjust the grid layout based on the container size when a Drawer is opened or closed. Essentially, it seems that YT adjusts the grid count based on the c ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...