Working with JSON data: including new child elements

Hey there, I'm just starting to work with JSON and TypeScript. I have a JSON object that needs processing, where each child value must be added up to set the parent values as the sum of corresponding attributes from its children.

 "parentValues":[{
 "number1": 0,
 "number2": 0,
 "parentId": 1,
 "childValues": [{
         "number1": 10,
         "number2": 20,
         "childId": 1
     },
     {
         "number1": 30,
         "number2": 40,
         "childId": 2
     }
 ]}]

After processing, it should look like this :

"parentValues":[{
 "number1": 10+30,
 "number2": 20+40,
 "parentId": 1,
 "childValues": [{
         "number1": 10,
         "number2": 20,
         "childId": 1
     },
     {
         "number1": 30,
         "number2": 40,
         "childId": 2
     }
 ]}]

Answer №1

Consider the following solution where we assume an array named parentValues containing objects:

let parentValues = [{
 "number1": 0,
 "number2": 0,
 "parentId": 1,
 "childValues": [{
         "number1": 10,
         "number2": 20,
         "childId": 1
     },
     {
         "number1": 30,
         "number2": 40,
         "childId": 2
     }
 ]}];


for(let i = 0; i < parentValues.length; i++ ) {
   for(let j = 0; j < parentValues[i]["childValues"].length; j++) {
       parentValues[i].number1 = parentValues[i]["childValues"][j].number1;
       parentValues[i].number2 = parentValues[i]["childValues"][j].number2;
   }
}

The logic is more important than the language used in this scenario.

This solution may not be perfect, but it gets the job done :)

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

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Building pagination functionality in AngularJS by sending parameters to an AJAX service: A step-by-step guide

I'm looking to learn how to implement pagination on a page with 10 records per page. Despite my efforts in searching online, I haven't been able to find any helpful resources explaining this concept. I would greatly appreciate a simple example or ...

React Navigation Browser

While developing my application, I encountered an error that I can't seem to resolve. It seems to be related to how I defined the routes in the code. Originally, the app had only one route, but after making changes to have multiple routes, I started g ...

Utilize json.net to parse a json file containing integer values in its structure

Requesting assistance with JSON file deserialization { "result": "success", "records": { "504498959": { "nif": 504498959, "seo_url": "triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda", "title": "Triworld - ...

Creating a set in AngularJS JSON data structure can be easily achieved by using the unique

Here is a JSON structure: { "list": [{ "name": "1", "type": ["A", "B"], }, { "name": "2", "type": ["A", "D", "C"], }, { "name": "3", "type": ["D", ...

Error in TypeScript: Circular reference in type alias 'Argument' in node_modules/classnames/index.d.ts at line 13:13

Need help troubleshooting an error while building my project. Can't find much information online to resolve this issue. I am using typescript 4.2.4 I can't locate the classnames/index.d.ts file in any directory, so I'm unable to make any ch ...

What is the method for entering JSON into a textarea using Selenium WebDriver and Java?

When working with Selenium WebDriver, typing text into a textarea can be done using the sendKeys method as shown below: driver.findElement(By.xpath("//textarea")).sendKeys("text to type"); However, in my situation, the text to be typed is in JSON format, ...

Insert into the associative array without any duplicate values

My aim is to add a new set of product records to an existing associative array, making sure each product is only included once. I came up with the following function, but it seems like too much code for such a simple task. Is there a PHP array function t ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

Developing a personalized collection of top picks and syncing them across multiple

Currently, I am in the process of developing a favorites list using a custom listview. ----------------------------------- <Item_Name> <favorite button> ----------------------------------- On the listView, there is an onItemClickListener. ...

Using a for-each loop to wait for the completion of an Ajax process

for (var i = 0; i < theTagNames.length; i++) { var url = baseURL + "?" + "jsoncallback=?" + "&method=flickr.photosets.getPhotos" + "&format=json" + "&api_key=" + api + "&photoset_id=" + theTagN ...

Setting parameters to Labels in Objective-C it is important to have unique

As someone new to iOS Programming, I have encountered an issue with assigning values to labels. Below is the data I receive from a service: ( { EmpName = Peter; Relation = SouthAfrica; }, { EmpName = Smith; Relation = WestIndies; }, { ...

Searching for data in Json using inner array in MSSQL

I am currently working with a table that includes a JSON column called ExtraTaskData. Here is an example of the JSON data: [ { "Type": "checkbox", "IsActive": true, "Name": "english", &qu ...

What is the best method to determine the total number of comparisons made during the organization of an array?

My task involves modifying a Java code snippet that sorts a set of random scores. I need to adjust the sortArray method to return the total number of comparisons made during calls to findMinLoc. Additionally, the main method should be updated to correctly ...

refresh my graph on the user interface once the service responds with JSON data

After obtaining the object successfully from my API, I have already displayed my custom graph component with default values. However, I need to update the 'chart1Title' of the graph component with the value of 'title' from the object. ...

Unit testing in NodeJS using Mocha where global variables injected from WebPack are utilized through the DefinePlugin feature

When using the WebPack.DefinePlugin to inject global variables, I've encountered an issue with integrating them into my Mocha unit tests. The tests don't recognize the global variables, and the Mocha documentation doesn't provide clear guida ...

"Encountered a 500 error while attempting to post

I'm encountering a 500 error when trying to post the results using curl curl -X PUT "http://xyz:8080/v1/test/086517a8-df1a-47a7-bcc7-056b08bd76d4/8911257e-7d7d-11e3-a26e-1e7184f6365b" -H Content-Type:application/json -d '{ "link":"http://xyz12.c ...

Please provide the JSON format for including tags in a status update on IBM Connections

I am attempting to programmatically post a status update to the activity stream within IBM Connections 4.0. I am currently trying to figure out where to place this JSON code: "tags":[{"objectType":"tag","displayName":"ibms"}], So far, I have tried the fo ...

Merging two NSDateFormatters to create a unified format

At the moment, I have two NSDateFormatters utilized in my application and I am looking for a way to consolidate them as they are both parsing the same date. I maintain a NSObject named UpcomingReleases where all my JSON information is stored. In Upcoming ...