What is the best way to flatten a 2D array using TypeScript?

If I have an array structured like this:

[0]:
    ["id_1"]:
        prop1: "abc"
        prop2: "def" 
    ["id_2"]:
        prop1: "ghi"
        prop2: "jkl"
[1]:
    ["id_3"]:
        prop1: "mno"
        prop2: "pqr" 
    ["id_4"]:
        prop1: "stu"
        prop2: "vwx"

Is there a way to transform it into an array with the format below?

[0]:
    key: "id_1"
    prop1: "abc"
    prop2: "def" 
[1]:
    key: "id_2"
    prop1: "ghi"
    prop2: "jkl"
[2]:
    key: "id_3"
    prop1: "mno"
    prop2: "pqr" 
[4]:
    key: "id_4"
    prop1: "stu"
    prop2: "vwx"

I attempted to use flatten functions referenced in this link, but I'm unsure of how to assign the correct keys to each flattened child element.

Answer №1

Without seeing the data structure, it's hard to confirm if it's correct. However, based on my assumption, you may achieve the desired outcome by using a combination of reduce and map functions.

let arr = [
    [{id_1: {prop1: 'abc', prop2: 'def'}}, {id_2: {prop1: 'ghi', prop2: 'jkl'}}],
    [{id_3: {prop1: 'abc', prop2: 'def'}}, {id_4: {prop1: 'ghi', prop2: 'jkl'}}]
];
  
function flatten(arr) {
  return arr.reduce((a, b) => {
    return a.concat(b.map(e => {
      let key = Object.keys(e)[0];
      return Object.assign({
        key
      }, e[key]);
    }))
  }, [])
}

console.log(flatten(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

Adjust the property to be optional or required depending on the condition using a generic type

const controlConfig = >T extends 'input' | 'button'(config: Config<T>): Config<T> => config; interface Config<TYPE extends 'input' | 'button'> { type: TYPE; label: string; ...

What causes different errors to occur in TypeScript even when the codes look alike?

type Convert<T> = { [P in keyof T]: T[P] extends string ? number : T[P] } function customTest<T, R extends Convert<T>>(target: T): R { return target as any } interface Foo { x: number y: (_: any) => void } const foo: Foo = c ...

Exploring the world of Typescript class decorators and accessing its content from within

Greetings, I am searching for a method to define a class in TypeScript and retrieve its value from within the parent. abstract class Base{ fetchCollectionName(): string{ // code here to return child class attribute value } } @Collectio ...

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

Switch on a single component of map array utilizing react and typescript

I am currently working on mapping a reviews API's array and I encountered an issue where all the reviews expand when I click on "read more" instead of just showing the clicked review. Since I am new to TypeScript, I'm not sure how to pass the ind ...

Switching between Python arrays and .NET Arrays

In my code, I have a Python function that returns a byte array in the form of array('c'). I am facing a challenge where I need to copy this array using System.Runtime.InteropServices.Marshal.Copy, which requires a .NET array. import array from ...

How can I fetch the current value on click from a collection of items in React js?

My challenge involves extracting the current color onClick from a list of colors, but instead of getting just one color, the entire list is returned. In my child component, I am mapping through the array as shown below: function Child({colorList, setBackgr ...

Attempting to transfer files to and from Firebase storage

Having trouble with my React Native app. I am trying to upload files, whether they are pictures or PDFs, but once uploaded, I can't seem to open them. However, "The files are getting uploaded to the storage." export const uploadToStorage = async (docu ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Automatically arrange TypeScript import statements in alphabetical order in WebStorm / PhpStorm

I am using tslint with the default config tslint:recommended and I am looking to minimize the number of rules I need to customize. Some rules require that imports be alphabetized: src/core/task/TaskMockDecorator.ts[2, 1]: Imports within a group must be a ...

Google Cloud PubSub does not automatically resend unacknowledged messages

The answer chosen for this particular question contains some pertinent details I currently have a subscription set up with the following parameters: https://i.stack.imgur.com/Bn0d4.png along with the following code snippet: const subscription = this.pub ...

Error in 'Unity3D': Array Index Out Of Bounds Exception occurred while attempting to modify sprite upon collision

Hey there, fellow Developers! I know this question has been asked before, but none of the answers provided a solution to my specific problem. Just to give you some context, I am new to unity and currently working on creating a brick breaker game. The issue ...

Navigating VSCode for Correct Import Setup

My root app directory has a structure consisting of the following folders: /app/ /environments/ Within the /app/ folder, there is a file named Helper.ts located in the helpers/ subdirectory: /app/helper/Helper.ts Inside this file, I attempted to import ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Struggling with a situation where the eloquent where clause is not accepting an

When attempting to pass an associative array to a where clause using Eloquent, I encountered an error. Here is a snippet of the code I am trying to execute: $where_array = [ 'last_name' => 'Smith', 'first_name&ap ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

Retrieve the jsonb value from a json structure that includes a json array in PostgreSQL

I am working with a JSON column that contains data like the following: {"image_pose_array": [{"image_name": "0026568143_WS.jpg", "image_pose": "EXTRA", "is_blurred": false, "is_dark": fal ...