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

Explicit final argument in TypeScript

Is it feasible to define a function in TypeScript 2.7.2 and above with variable parameters, but ensuring that the final parameter has a specific type? I am attempting to craft an ambient TypeScript declaration for a JavaScript library that utilizes functi ...

Transforming CSV Arrays into JSON using Node.js

Currently, I am extracting information from a URL that contains a csv file. The data format that I am trying to retrieve looks like this: To accomplish this task, I am utilizing Node.js and making use of the nodejs-requestify package: https://www.npmjs.co ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

The term "containerName" in SymbolInformation is utilized to represent the hierarchy of

In my quest to make the code outline feature work for a custom language, I have made progress in generating symbols and displaying functions in the outline view. However, my next challenge is to display variables under the respective function in the outlin ...

Implementing a hierarchical data retrieval system in MongoDB with Node.js to retrieve data in the format of Category > Subcategory > Product

I have 3 unique models that are interrelated and I would like to connect them by their respective IDs. The desired response is provided below. Below is a sample dataset for reference: This is the JSON format I require in the response "categoryData": ...

The value stored within an object does not automatically refresh when using the useState hook

const increaseOffsetBy24 = () => { setHasMore(false); dispatch(contentList(paramsData)); setParamsData((prevState) => ({ ...prevState, offset: prevState.offset + 24, })); setHasMore(true); }; This function increment ...

A guide on elegantly pausing for the completion of .map() function and generating fresh keys within the array[index]

I am currently working on generating an array with the following values: { name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array and initializing the array with these initial values: ...

What is the best way to include arrays in VueJS?

Currently, I am working with two arrays in my Vue application. The first array called desserts lists all the desserts that I have. The second array, moreDesserts, displays checkboxes with values. When a user selects a checkbox, the value is added to the se ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...

JavaScript: Converting an array of strings into an array of objects with proper formatting

After scanning barcodes, I have an array of strings that currently contains the following data: var array = ['NEW', '1111', 'serial1', 'serial2, 'NEW', '2222', 'serial3', 'serial4'] ...

Resolving the issue of missing properties from type in a generic object - A step-by-step guide

Imagine a scenario where there is a library that exposes a `run` function as shown below: runner.ts export type Parameters = { [key: string]: string }; type runner = (args: Parameters) => void; export default function run(fn: runner, params: Parameter ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

Angular 2 Unit test issue: Unable to resolve parameters for 'RequestOptions' class

I am currently working on testing a simple component that has some dependencies. One of the requirements is to provide certain providers for the test. /* tslint:disable:no-unused-variable */ import { By } from '@angular/platform-browser&ap ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...

How to handle a property that is not found in a combined type in TypeScript?

In this scenario using TypeScript: interface EmotionsOkay { emotion: string; okay: "yap"; } interface EmotionsNotOkay { emotion: string; } type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay; const areYouOkay = (test: UndetereminedEmotion) =& ...

Encountered an issue during the transition from Angular 7 to Angular 9

After following the advice in the second response of this discussion, I successfully upgraded to Angular 9. However, I am now encountering an issue in the browser console when running my project. Package.json "dependencies": { "@angular-devkit/build- ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...