Manipulating Typescript JSON: Appending child attributes and showcasing them alongside the parent item attributes

Here is a JSON data that needs to be processed:

var oldArr =
[{
"careerLevel": "Associate",
"careerLevels": [
    {
        "201609": 21,
        "201610": 22,
        "careerID": "10000120"
    },
    {
        "201609": 31,
        "201610": 32,
        "careerID": "10000130"
    }]}];

Now, let's convert the above JSON to:

var newArr= [{
"201609": 52,
"201610": 54,
"careerLevel": "Associate",
"careerLevels": [
    {
        "201609": 21,
        "201610": 22,
        "careerID": "10000120"
    },
    {
        "201609": 31,
        "201610": 32,
        "careerID": "10000130"
    }]

}];

I am attempting to perform summation using the reduce() function:

var arr = [{x:1},{x:2},{x:4}];

  arr.reduce(function (a, b) {
    return {x: a.x + b.x};
  });

  console.log(arr); //Outputs the same initial array

var reduceArr = oldArr.reduce((sum, item) =>
const total = sum + item.201609; // this is giving me an error

);

Although I have some knowledge of the reduce function, I am still relatively new to this concept.

Answer №1

Surprisingly, nobody took a shot at solving this particular question. It's interesting that there were quick downvotes. Here is the code snippet I've come up with to achieve the desired outcome:

 var oldArr =
       {

       "careerLevel": "Associate",
       "careerLevels": [
           {
               "201609": 21,
               "201610": 22,
               "201611": 23,
               "careerID": "10000120"
           },
           {
               "201609": 31,
               "201610": 32,
               "201611": 33,
               "careerID": "10000130"
           }]
   };



   var finalSummedJson = JSON.stringify(SummationProcessing(oldArr));
   return finalSummedJson;


}

// Summation Logic

 function SummationProcessing(oldArr) {
  let sumArr = [];
  let allKeysInLevels = Object.keys(oldArr.careerLevels[0]);
  let uniqueKeys = allKeysInLevels.filter((key, index) => {
      return parseInt(key) > 0 && allKeysInLevels.indexOf(key) == index
  });

  uniqueKeys.forEach(uniqueKey => {
      var sumKey = oldArr.careerLevels.reduce((acc, val) => {
          return acc + val[uniqueKey];
      }, 0);

      sumArr.push(sumKey);
  });

  var reducedData = oldArr.careerLevels.reduce((redArr, inpArr) => {
      var keysToFilter = Object.keys(inpArr);
      var keyysss = keysToFilter.filter((key, index) => { return parseInt(key) > 0 && keysToFilter.indexOf(key) == index });
      keyysss.forEach((element, i) => {
          if (!redArr[element]) {
              redArr[element] = sumArr[i];
          }
          // });
      });
      return redArr;

  }, {});
  // console.log("reducedData", JSON.stringify(reducedData));

  Object.keys(reducedData).forEach(key => { oldArr[key] = reducedData[key] });
  return oldArr;

  // console.log("finalArr", oldArr);
}

And the end result turned out to be:

{ "201609": 52, "201610": 54, "201611": 56, "careerLevel": "Associate", "careerLevels": [{ "201609": 21, "201610": 22, "201611": 23, "careerID": "10000120" }, { "201609": 31, "201610": 32, "201611": 33, "careerID": "10000130" }] }

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

Experience the Versatility of Android Mediaplayer Playing Local Files

I'm looking for guidance on how to play local audio/video files in Android Mediaplayer. I've managed to stream audio/video from URLs using a Variable storing the URL, but I'm unsure how to do it with local files. How can I utilize the localF ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Is the AJAX call returning JSON data?

Currently, I am utilizing AJAX technology to scrape player names and their respective ratings from a website. The approach I have chosen involves having AJAX return a JSON object which is then manipulated using jQuery to append each element of the JSON obj ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

Using Angular Ngrx to Retrieve and Showcase a Selection of Choices from a Java API

When accessing the Java API at localhost://company/products/123/fetchOptions, you can expect a response similar to the following: { "Increase": true, "Decrease" : true, "Like" : true, "Dislike" : true, "Old" : false, "Others" : true } Using Angula ...

Issue with the Mat paginator items per page functionality not functioning properly in Angular 9

I have encountered an issue where changing the items displayed per page on a table I'm rendering from an observable is not functioning as expected. Despite trying methods such as ngAfterViewInit and calling page events, I did not see any changes. ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

Implementing AsyncTask in Android to establish a connection with MySQL database through PHP

Looking for assistance on implementing this with AsyncTask? You can check out this tutorial: . Having trouble getting it to work on android 4.0.3. Any help would be greatly appreciated. Thank you in advance. ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

Function overloading proving to be ineffective in dealing with this issue

Consider the code snippet below: interface ToArraySignature { (nodeList: NodeList): Array<Node> (collection: HTMLCollection): Array<Element> } const toArray: ToArraySignature = <ToArraySignature>(arrayLike: any) => { return []. ...

What is the proper classification for me to choose?

Apologies for the lack of a suitable title, this question is quite unique. I am interested in creating a function called setItem that will assign a key in an object to a specific value: const setItem = <T, U extends keyof T>(obj: T) => (key: U, ...

Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object const obj = {a:1, b: 2, c: 3}; const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2} Unfortunately, achieving this task with type safety in TypeScript can be c ...

Is there a way to establish a pre-defined key in a mat-table?

I am fetching data from an API and I need to display it in a key-value format on a mat table. The keys are predefined and not provided by the API. The data retrieved from the API is shown here: image1 I want to display it on a mat table like this: mat ta ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Harness the power of JSON data within your iOS applications. Unleash its capabilities

After developing a web service that I believed was returning JSON data, I examined the output: {"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}} Based on my understanding, this appeared to be valid JSON. ...

Comparison between JSON and Ruby validations: Understanding error definition

When attempting to capture a validation message using $.parseJSON(xhr.responseText).errors, I am receiving an alert message showing "undefined" and I am not sure why. Here are the validations being used: validates :upload_file_name, :presence => tr ...

Creating a dynamic multi-line list in Ionic application is a breeze!

I'm a beginner in Ionic and I am interested in creating a Multi-line List similar to how we generate list-views in Android with custom views and using an Array of custom objects programmatically. Can Multi-line Lists be generated with data from an Ar ...

Reading a JSON object from a SQL database and transforming it into a Java class: A step-by-step guide

I have set up a column of type varchar(max) in the table within my Database, utilizing 'for JSON Auto' to store all the columns of that table as a JSON object, including Foreign keys. The JSON I generated now appears like this: { "widge ...