Typescript: Managing nested arrays of objects

I am working with a sample array of objects as shown below:

let arr = [{id: 1,name: 'Test',segment: 'test',subCategory: [{id: 1,name:'Test1',segment:'test1'}]}]

My goal is to reformat this array into the following structure:

let newArr = [{link: 'test', name: 'Test',subCategory: [{link: 'test1',name: 'Test1'}]}]

Can anyone provide an easy way to achieve this in typescript?

Answer №1

To achieve the desired outcome, one can utilize the Map method:

const originalArray = [
  { id: 1, name: 'Test', segment: 'test', subCategory: [{ id: 1, name: 
'Test1', segment: 'test1' }] }
];

const newArray = originalArray.map(item => {
  return {
    link: item.segment,
    name: item.name,
    subCategory: item.subCategory.map(subItem => {
      return {
        link: subItem.segment,
        name: subItem.name
      };
    })
 };
});

console.log(newArray);

Answer №2

To achieve the desired output, employing a recursive strategy is recommended. Utilizing the map function in JavaScript can facilitate this process:

The recursive approach is capable of handling complex nested structures effortlessly.

let arr = [{
    id: 1,
    name: 'Test',
    segment: 'test',
    subCategory: [{
        id: 1,
        name: 'Test1',
        segment: 'test1'
    }]
}]

const formatResult = (arr) => arr.map(obj => {
    const { id, segment, subCategory, ...rest } = obj
    const subCategoryFormatted = subCategory ? formatResult(subCategory): null;
    
    return subCategoryFormatted 
            ? { ...rest, link: segment, subCategory: subCategoryFormatted }
            : { ...rest, link: segment };
})

console.log(formatResult(arr));

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

"Exploring the versatility of PHP arrays with a mixture of images

I'm attempting to showcase an image in a PHP Array. Here's what I have: View: <?php include "controllers/Autos.php"; ?> <!DOCTYPE html> <html> <head> <title>Autos</title> </head> <bo ...

Node.js and Mongoose encounter difficulties in comparing documents

I am in the process of iterating through an array of documents that I have queried to check if each element is present in another array of documents that I have also queried My model structure includes : var dataTypeSchema = new Schema({ name : Stri ...

What is the best way to generate an array of integers by using strings as the index values?

I am struggling to find information on a particular concept in C programming because I don't know what it's called. Currently, I am working on a project in C. I have an array of integers that I want to name using characters; for example char ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

What is quicker: storing a large 10^5 size array in an Android app and searching within it, or executing search queries to retrieve data from a database?

I am currently developing an application with a database containing over 15,000 rows and 20 columns. When a user performs a search within the app, I have two options: 1. Save all data from the database when the app is running and then search for the user ...

What is the best way to convert the results of a Get-ADComputer PowerShell query into a JSON format that includes the IP address and a parent object such as

After running the following ps1 script: Import-Module ActiveDirectory Get-ADComputer -Filter "OperatingSystem -Like '*Windows Server*' -and Enabled -eq 'True'" | Select-Object Name, DNSHostName | ConvertTo-Json | Out-File &quo ...

JavaScript - Assigning a class to an element based on an array

I am facing a challenge where I need to assign classes from an array to an element in sequential order. The issue is that once I reach the end of the array, I do not know how to loop back to the beginning and start over. Here is my current code: var bac ...

Is there a way for me to accurately obtain those values?

If I have received this output from the Chrome console log, how can I extract those specific values? Is there a way to retrieve the value following the first ":" character? (Note that sometimes there may be ":" within a URL value - is there a method to fil ...

What is the best way to extract all numeric values from a document and store them in an array?

When dealing with an input file that may have spaces or new lines between each number, parsing through the file to grab all elements and place them inside an array can be a challenging task. Take for example the content of the file: input.txt 2 3 4 4 3 2 ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

The Concept of Static Block in TypeScript

For the purpose of testing Network Encoding/Decoding Logic, I have implemented a pair of test cases in both Java and JavaScript. These tests utilize Data Providers which essentially consist of various Constants. In my Java test case, I have a Data Provide ...

Tips for sending an array of objects to Node.js and ultimately storing it in a MongoDB document

Previously, I was able to send individual objects to a nodejs server using req.body.object. However, I'm encountering an issue when trying to send an array of objects to a mongo document using req.body.array. On my front end, I have successfully save ...

Manipulate a Nested Array in PHP

I initialized an array and nested it inside another array. My intention was to modify the inner array later on, but for some reason, the modifications are not taking effect. Below is the initialization code snippet: $arr_row_name = array(); for($nrow=0; ...

Sort an array of characters using the bubble sort algorithm

Attempting to implement a bubble sort on a 2D character array in C without utilizing any standard library functions. However, the provided code does not result in any successful sorting when compiled and executed. The array 'Strings' is defined ...

Connecting ngModel input to an array within a form in Angular

I'm looking to implement *ngFor binding to dynamically create additional forms using an array and ngModel input. My goal is that when a value is selected, I can click a button to display a new form with a different value. Does anyone have any ideas ...

The type '...' cannot be assigned to the type '...' for argument ts(2345)

type FruitName = 'apple' | 'banana'; interface Fruit { name: FruitName; } const apple = { 'name': 'apple', }; function test(fruit: Fruit) { console.log(fruit.name); } function main() { const name: ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions? type ProductType = { props: | { ...

Invalid Redux store: Element type is not valid; a string type is expected

I am running into an issue while setting up the redux store with typescript for the first time. The error message I am encountering is: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ...

A collection of objects in TypeScript with a reference and the ability to add new objects using the

Recently, I've come across an issue in my code while working with custom objects and arrays of them. I have identified a scenario where the push() method works fine and another where it doesn't. Scenario 1 (working as expected): class MyObject{ ...