Utilizing TypeScript to extract elements from nested arrays

I'm working with an array structured like this:

[{
        "id": 1,
        "city": [{
                "name": "BERLIN",
            }
        ],
    }, {
        "id": 2,
        "city": [{
                "name":: PARIS,
            }
        ],
    }, {
        "id>>: 3,
        "city"': [{
                    "name": '""""LONDON",
                    
               . 'EXETER',
            },
        ],
    }

My goal is to extract specific values from the above data:

[
    {id: 1, city: {name: "BERLIN"}, 
    {id: 2, city: {name: "PARIS"},
    {id: 3, city: {name: "LONDON"},
    {id: 3, city: {name: "EXETER"} 
]

I've attempted using map functions but haven't been able to achieve the desired outcome.

If you have any insights or solutions to offer, I would greatly appreciate your assistance.

Thank you.

Answer №1

One way to achieve this is by utilizing the flatMap() method:

const data = [{
  "id": 1,
  "city": [{
      "name": "MADRID",
    }],
}, {
  "id": 2,
  "city": [{
      "name": "ROME",
    }],
}, {
  "id": 3,
  "city": [{
      "name": "TOKYO",
    }, {
      "name": "SYDNEY",
    }],
}];

const processedData = data.flatMap(({id, city}) => city.map(c => ({id, city: c})));

console.log(processedData);

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

What is the best way to change a List of integers to an array of strings in C#?

Looking for a simple solution to change a List<int> into a string array. Here's what I currently have: var my_list = new List<int>(); my_list.Add(1); my_list.Add(2); my_list.Add(3); string[] my_array = new string[my_list.Count]; for(var ...

Encountering a Typescript error when trying to pass a function as a prop that returns SX style

Imagine a scenario where a parent component needs to pass down a function to modify the styles of a reusable child component: const getStyleProps: StyleProps<Theme> = (theme: Theme) => ({ mt: 1, '.Custom-CSS-to-update': { padding ...

Applying style to HTML elements using Typescript

My issue involves working with a combination of HTML and TypeScript. <ion-card class="ionCard" *ngFor="let item of libraries"> <ion-card-header> {{getLibraryName(item.locationName)}} </ion-card-header> ...

Determining the type of a single deconstructed variable from an object

My useForm hook is designed to take an object and return several useful functions back, including that object as a state. However, due to TypeScript limitations, the specific type from the initial object cannot be returned because useForm accepts dynamic o ...

Typescript encounters difficulty locating the Express module

My venture into creating my debut NodeJS application has hit a roadblock. Following advice from multiple blogs, I have been attempting to build my first nodejs app in typescript by following the steps below: npm install -g express-generator npm install - ...

Ensuring TypeScript object types are safe by requiring all keys to be within an array of values

When working with Typescript ^3.8, we have an interface defined as follows: interface IEndpoint { method: 'get'|'put'|'post'|'patch'|'delete', path: string } Additionally, there is a constant declared like ...

Python code to identify elements in an array with prices above the mean value

Currently enrolled in a Python course, I'm seeking assistance with the following task: given a list of food items along with their calorie and price information in the format [name, calories, price], I aim to create a Python function that will return ...

The error message "Property 'then' is not available on type 'void' within Ionic 2" is displayed

When retrieving data from the Google API within the function of the details.ts file, I have set up a service as shown below. However, I am encountering a Typescript error stating Property 'then' does not exist on type 'void'. this.type ...

Sorting data structures using the heapsort algorithm within the framework of an array in the

I am currently attempting to implement Heapsort in order to sort a structure of character arrays read from a text file. My algorithm successfully works with integers, but when I switch to 'char' type, it does not display any results or errors. A ...

Efficiently modifying array data

Currently, I have a script that inserts data into the database three times using function calls. The code functions correctly without any issues. // Set the function parameters. $client_id = $_SESSION['user']['client_id']; $params = a ...

How can we determine if a given URL contains 'at least one' of the strings in the specified array using strpos?

I have a variable $url (which I do not control) that contains a URL as a string. For example: $url = 'http://www.youtube.com/watch?v=rSnzy2dZtsE'; I have a list of hosts (example.com) that I need to compare against the $url to see if any of the ...

Having trouble with the "\" not working? Is there a way to use just one backslash instead?

I'm struggling with a little issue in Typescript - how can I use just one backslash? What I'm aiming for is an url pattern like this: "\/hello\/"+ urlRoute + "\/([0-9]*)", But when I attempt it, I end up with "/hello/"+ urlRoute ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

What is the method for importing or requiring standard node modules in TypeScript?

How can I effectively use the require function in typescript with standard NPM modules? I am currently attempting to utilize the debug package. I have installed it from npm and also ran tsd install debug. However, I am facing issues where the syntax works ...

What is the process for accessing a child within an optional field?

I am working with the following data type: export type GetWeeklyArticleQuery = { __typename?: 'Query'; weeklyArticle?: { __typename?: 'WeeklyArticle'; date: any; tags: Array<string>; title: ...

Showing Angular 2 inputs in string format

I am currently tackling a challenge with a project that utilizes Angular 2. The client has requested that the numbers entered in the input tags be displayed as strings with commas and decimals. However, since the data is being sent to and retrieved from ...

Encountering a typescript debug configuration issue in visual studio code while working on a node js

Currently, I am using Visual Studio Code editor version 0.5 and have a debug configuration file set up as follows: { "name": "Launch application",     "type": "node",     "program": "src/server/app.ts",     "stopOnEntry": false,     "sour ...

What is the process for delineating a smaller object within a larger one?

The current data structure I am handling: this.currentData = [ { "1304": { "id": 6458, "data": "Data1", "created_at": "2020-10-20 23:16:38", "updated_at": & ...

What is the best way to set up the typeRoots option for proper configuration

I have a unique yarn monorepo structure that is oddly shaped. Here's how it's set up: monorepo root ├── frontend │ ├── dashboard <-- not managed by yarn workspaces │ | ├── src │ | ├── node_modules │ ...

Struggling with Primeng's KeyFilter functionality?

I've implemented the KeyFilter Module of primeng in my project. Check out the code snippet below: <input type="text" pInputText [(ngModel)]="price.TintCost" [pKeyFilter]="patternDecimal" name="tintCost" required="true" /> Take a look at my Typ ...