How to efficiently flatten nested arrays using Angular 8 and Typescript

I'm currently dealing with nested JSON data that I need to flatten for easy display in a table format, without using dropdowns.

The structure of the data is somewhat similar to this...

0:
ID: 4
Date: "2019-08-09T00:00:00"
Data:
Year: 2019
Identification: "F31073"
nestedArray: Array(1)
   0:
      array1ID: "31"
      array1Code: "073"
      nestedArray2: Array(4)
      0:
        array2info: 24
        nestedArray3: Array(8)
          0:
          array3Identifier: "ECF5EE44-50E1-4F07-AB38-CF7A60A6276F"
          array3Number: 31
          arrayThreeIndicator: "N"
          nestedArray4: Array(1)
             0:
             array4Info: "31"
             array4Code: "073"

I've explored various solutions but none have provided me with a flat dataset.

UPDATE: Below is the JSON data that I am looking to flatten, ensuring that all fields from each nested array are duplicated and visible without any nesting:

"[{"FileCustomerIdentifier":4,"TransmissionDate":"2019-08- 
 09T00:00:00","TransmissionData":"{\r\n  \"cropYear\": 2019,\r\n  
 \"originatorIdentification\": \"F31073\",\r\n  \"farm\": [\r\n    {\r\n      
 \"administrativeStateFsaCode\": \"31\",\r\n      
 \"administrativeCountyFsaCode\": \"073\",\r\n      \"farmNumber\": 
 4609,\r\n      
 \"tract\": [\r\n        {\r\n          \"tractNumber\": 24,\r\n          
 \"field\": [\r\n            {\r\n              \"cluIdentifier\": 
 \"ECF5EE44-50E1-4F07-AB38-CF7A60A6276F\",\r\n              
 \"fieldNumber\": 
 31,\r\n              \"cluProducerReviewRequestIndicator\": \"N\",\r\n              
 \"agriculturalProductionPlan\": [\r\n                {\r\n                  
 \"stateAnsiCode\": \"31\",\r\n                  \"countyAnsiCode\": 
 \"073\",\r\n                  \"coreProductCode\": \"0102\",\r\n                  
 \"coreProductTypeCode\": \"0794\",\r\n                  
 \"productIntendedUseCode\": \"0007\",\r\n                  
 \"originalReportedAcreage\": 109.93,\r\n                  
...
" 

Any assistance on this matter would be highly appreciated!

Answer №1

For a situation where your nested array keys have the same structure, you can achieve flattening recursively like this:

type NestedArray = { items: NestedArray[] }[]

function flattenNestedArray(nestedData: NestedArray) {
  let flattenedArray = [];

  for (const { items, ...restData } of nestedData) {
    flattenedArray.push(restData);
    if (!items || !items.length) continue;
    flattenedArray = flattenedArray.concat(flattenNestedArray(items))
  }

  return flattenedArray;
}  

const flattenedData = flattenNestedArray(yourNestedData);

This approach allows you to handle nesting in arrays efficiently.

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

Convert data into a dictionary by iterating through it in a foreach loop within C# MVC

Currently, I am facing an issue within my C# MVC application in a controller. Dictionary<string, string> dictionaryList = new Dictionary<string, string>(); getJsonData data = new JavaScriptSerializer().Deserialize<getJsonDa ...

Modify the directory for script files in index.html within @angular-cli

I am currently modifying the default path from index.html to /Views/Home/index.cshtml. This change is part of hosting an Angular app using ASP.NET Core 2.0. The issue I am facing right now is that all script file paths generated in index.cshtml when runni ...

Leveraging @ContentChildren in Angular 2 to sort through a component's contents

I am currently working on implementing a search component that can trigger a search(term: string) function on specific child components. If the search on the child fails, the function will return null; otherwise, it will return a reference to the child. M ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

The behavior of the separator operator in TypeScript is puzzling

Highlighted below is the code snippet: declare function test1<T extends unknown[]>(value: T): T const res1 = test1([1, 2, 3]) // type is number[] declare function test2<T extends unknown[]>(value: [...T]): T const res2 = test2([1, 2, 3]) // t ...

The image path for "tour-x-b-cover.jpeg" at http://localhost:4200 is broken and the image is not displayed

I am facing an issue with my table list of tours where all the required information is displayed except for the image Cover. Despite checking everything, I cannot seem to figure out why the image path is broken. Initially, I suspected that there might be a ...

Looking for a method to efficiently populate an array with values in Typescript

Here is an example of how I work with arrays in my code: var alphas: string[]; alphas = ['abc1', 'abc2', 'abc3']; // (this array can be changed) My modal class looks like this: export class Team { TeamName: string; } To ...

Utilize AWS CDK Step Function Task to incorporate a list of objects within the DynamoPutItem operation

I am currently facing a challenge with using the DynamoPutItem task to insert an entry that includes a list of objects as one of its attributes. I have searched online for examples of this but have not found any, leading me to question if it is even possib ...

Managing checkboxes using the useState object

I am currently working on displaying checkboxes using the .map() function to retrieve data from a JSON file. My current challenge is that when I click on a checkbox, it stores the clicked checkbox in the state object. However, if I click on another checkb ...

Obtaining only string values when looping through JSON information

JSON: { "status": "success", "data": { "9": { "1695056": { "id": "1695056", [...] }, "csevents": { "2807": { "id": "280 ...

Exploring the depths of OfficeScript: A guide to accessing nested objects using interfaces and setValues()

Currently, I am diving into Excel Office Script through API requests. Even though I'm not a programmer by trade, I find myself facing challenges that I wouldn't encounter in jQuery. The struggle lies in structuring objects correctly to set values ...

Incompatibility with semantic versioning and npm versions 5 and higher

Could you explain the necessity of using NPM 5 or later to prevent issues with semantic versioning? How does the package-lock.json file help in avoiding this problem? Would using the same package.json file on all development machines for a project also r ...

Encountered a SyntaxError stating 'Unexpected token' while attempting to parse a jsonp response

I have recently developed a JSON webservice using ASP.NET. URL http://mydomain:21130/JSONdata.aspx?Option=GetListRootMenus The data returned is as follows: {"NumberOfMenu":"2", "Menus":[{"MenuKey":"menu_home", "MenuLevel":"1" },{"MenuKey":"menu_info", " ...

Issues encountered when running tests on asynchronous functions in Angular utilizing Jasmine

Currently, I'm facing errors in running unit tests for my Ionic 4 app using Jasmine. It seems like there are issues with the async/await functions as most of my tests are failing with the error message: "Error: Timeout - Async function did not complet ...

Loading Google Books JSON data into a ListView

Currently, I am utilizing the Google Books API to search for books. However, I am encountering an issue when trying to populate my ListView with the searched books as it is throwing an error specifically in the onPostExecute method, but I am unable to iden ...

Step-By-Step Guide on Creating a Data Post Using HttpUrlConnection

Here is an AJAX code snippet I have: $.ajax({ url: 'http://www.whoisxmlapi.com/whoisserver/WhoisService', dataType: 'jsonp', type:'POST', data: { domainName: 'domaindomanin.com', outp ...

What is the most effective method for caching a getter function (excluding decorators)?

Creating a getter cache can help optimize performance by storing and reusing the value rather than recalculating it each time. I am seeking the most efficient method to implement a getter cache without relying on decorators. While there are libraries that ...

Changing Json Data into SQL Database Table

I'm looking for a way to dynamically generate SQL queries. I came across this helpful tool: http://querybuilder.js.org/demo.html Here is the JSON object I have: { "condition": "AND", "rules": [ { "id": "name", "field": "name", ...

Creating a Jest TypeScript client mock that returns an array filled with undefined elements instead of the expected resolved values

At the moment, I am in the process of writing tests for a helper function that I created. This function takes a client and an array as parameters. Essentially, the function is designed to retrieve all tasks for all sites on a website. So far, the method is ...

Effective ways to decode Magento's JSON web services on an Android platform

Learning android for the first time and struggling to extract data from Magento webservices. Using ksoap2 library to fetch data from webservices. Here is the code snippet I utilized to retrieve data. In async task, web service is invoked to receive respon ...