Transform a nested array of objects into a distinct set of objects based on the data in JavaScript or TypeScript

I have a unique situation where I am dealing with a double nested array of objects, and I need to restructure it into a specific array format to better align with my table structure.

Here are the current objects I'm working with and the desired result structure:

let newData = {
  data: {
    summary: [
      // Objects go here
    ]
  }
};


// Result array structure
let result = [
  // Desired object structure goes here
];

I'm looking for guidance on how to efficiently iterate over these objects to achieve the desired structure. Given that I have a large amount of data, what would be the best approach to minimize the number of iterations needed?

Answer №1

Give this code a try and observe the results. If you prefer, you can streamline the code into a single function.

const updatedData = newData.data.summary.map(item => {
  const updatedItem = {
    code: item.code,
  }
  item.data.forEach(d => {
    updatedItem[`${d.group}${d.currency}`] = d;
    d.amount = d.amount || "$0.00"; // setting default value for amount
    d.total = d.total || 0; // setting default value for total
  })
  return updatedItem;
});
console.log(JSON.stringify(updatedData));

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

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

The React component does not trigger a re-render

Using React Redux, I am able to pass values successfully. However, the component I intend to render only does so once. Interestingly, when I save my code in VSCode, it renders again and the data displays on the page as expected. return ( <div classN ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Looking for a condensed version of my app script to optimize speed and efficiency

In my script, users input data and run the script by clicking a button. The script then appends the data to two different tabs and clears the data entry tab. However, I encountered an issue where I had to manually hard code each cell for appending, causi ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

The fonts in node.js are not functioning as expected, without displaying any error messages

I'm having trouble implementing custom fonts on my website. Despite following the correct file structure, the fonts do not seem to be loading. My project files are organized in the following manner: https://gyazo.com/5ee766f030290e5b2fa42320cc39f10b ...

What is the proper syntax for implementing the $q.all method?

During my interview, I was asked the following question. Can you identify the correct syntax for using the $q.all method? • $q.all([promise1(), promise2]).then((values) => { … }); • $q.all("promise1", "promise2").then((values) => ...

Increasing the variable by 1 in PHP will result in the variable value being incremented to 1

My issue involves incrementing a variable in my .php file code that changes the value in the database. After incrementing the acc_points variable by one, it updates the data in the MySQL database and then returns the data to the JavaScript, which alerts th ...

Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone. check('phone') .not() .isEmpty() .withMessage('Phone should not be empty') .custom(async phone => { const phoneCheck = await ...

Swap out the <a> tag for an <input type="button"> element that includes a "download" property

I have been working on a simple canvas-to-image exporter. You can find it here. Currently, it only works with the following code: <a id="download" download="CanvasDemo.png">Download as image</a> However, I would like to use something like th ...

The strcmp function does not effectively compare two adjacent strings within an array of character pointers

I have been working on a C program to alphabetize a 10 string array, but I am facing issues when using strcmp(). The problem lies in the line where the string-handling comparison function does not compare strings on the right side. Below is my current co ...

How can I define a schema attribute for a controller in Express JavaScript?

Hello, I am brand new to exploring stack overflow and the world of development. I have been self-teaching myself how to code using React and Express, so please forgive me if my question seems basic or implausible. I still have many fundamental gaps in my k ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Angular- Product Details

I'm currently expanding my knowledge of angular (utilizing the ionic framework with phone gap included) and I'm working on developing a single application that displays a list of data. When a user clicks on an item in the list, I want to show the ...

What is the best method for implementing a Twitch <script> tag within Vue.js?

In an effort to replicate the functionality I achieved in Angular here, I am now attempting to do so within Vue.JS (2.6+). My goal is to utilize the Twitch API for embedding a Stream, which currently only offers usage through inline HTML: <script src= ...

I've noticed that the NextJs router appears to be significantly slower in comparison to React

I currently have a website that is built in both React Js and Next Js. The issue I am currently encountering is that the router in NextJs is noticeably slower compared to react-router-dom. It takes almost 2-3 seconds to change the route. To experience th ...

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

Organize arrays within arrays in Javascript

My array of data is structured for visualization as shown below: var Dataset1 = [ { "commentBy": "saurabh", "comment": "Testing", "datestamp": "07/07/2017", "weekcount": 1 }, { "commentBy": "raman", "comment": "Planning", ...