Efficiently transforming a nested object array into a single dynamic array

// I have a collection of various objects

_id: "5e5d00337c5e6a0444d00304"
    orderID: 10355
    orderDate: "2020-03-02"
    user:
       _id: "5e2e9699a648c53154f41025"
       name: "xyz1"
       email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="08696a6b6c6d486f65696164266b6765">[email protected]</a>"
       mNumber: 12336

// and I need to consolidate this into a single array

orderID: 10354, 10355
orderDate:"2020-03-02","2020-03-02"
name: "xyz", "xyz1"
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="79181b1a1d391e14181015571a1614">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d3d0d1d6d7f2d5dfd3dbde9cd1dddf">[email protected]</a>"
mNumber: 1234536, 12336

My goal is to export this data to an Excel sheet with headers for id, name, email, and more like so:

orderID    orderDate    name   email           mNumber
10354      2020-03-02   xyz   <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e9888b8a8da98e84888085c78a8684">[email protected]</a>   1234536
10355      2020-03-02   xyz1   <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11707372757451767c70787d3f727e7c">[email protected]</a>   12336

How can this be achieved in Angular?

Answer №1

If my understanding is correct, you are able to achieve something like this,

objs = [
  {
    _id: "5e5d00337c5e6a0444d00304",
    orderID: 10354,
    orderDate: "2020-03-02",
    user:
    {
      _id: "5e2e9699a648c53154f41025",
      name: "xyz",
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c1c2c3c4e0c7cdc1c9cc8ec3cfcd">[email protected]</a>",
      mNumber: 1234536
    }
  },
  {
    _id: "5e5d00337c5e6a0444d00304",
    orderID: 10355,
    orderDate: "2020-03-02",
    user:
    {
      _id: "5e2e9699a648c53154f41025",
      name: "xyz1",
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38281808786a3848e828a8fcd808c8e">[email protected]</a>",
      mNumber: 12336
    }
  }
];
const arr = [];
for (const o of objs) {
  arr.push([
    o.orderID,
    o.orderDate,
    o.user.name,
    o.user.email,
    o.user.mNumber
  ]);
}
console.log(arr);

This is the resulting array form,

[ [ 10354, '2020-03-02', 'xyz', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcecdcccbefc8c2cec6c381ccc0c2">[email protected]</a>', 1234536 ],
  [ 10355, '2020-03-02', 'xyz1', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="442526272021042329252d286a272b29">[email protected]</a>', 12336 ] ]

In essence, it's simply an iteration process.

I will introduce another approach here. In this scenario, instead of listing all values for each row, you specify the values that should not be included in the row. You can utilize a recursive function to navigate through the objects in such cases. fields is the object where you define which values to include and exclude. Here is an example:

const fields = { _id: false, user: { _id: false} }
function toRowRec(obj, fields) {
  let row = [];
  const keys = Object.keys(obj);
  for (const k of keys) {
    if (!fields.hasOwnProperty(k)) {
      row.push(obj[k]);
    } else if (typeof obj[k] === 'object' && obj[k] !== null) {
      row = row.concat(toRowRec(obj[k], fields[k])); 
    }
  }
  return row;
}
let arr = []
for (const o of objs) {
  arr.push(toRowRec(o, fields));
}
console.log(arr);

The input objs remains the same as before, and the output generated will be identical to the previous one.

You'll notice that I'm excluding specific keys that I want to appear in the row by checking if the key exists in the fields object.

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

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...

Enforcing Type Safety on String Enums in Typescript Using the 'const' Assertion

I am trying to use an enum for type checking purposes. Here is the enum I have: enum Options { Option1 = "xyz", Option2 = "abc" } My goal is to create a union type of 'xyz' | 'abc'. However, when I attempt to d ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...

File upload not functioning correctly with Angular 7 MEAN stack when using multer middleware

I am currently using the multer middleware for file upload in my Angular mean stack project. However, I am facing an issue where I am unable to retrieve req.file but can successfully access req.body, indicating that the file is not being uploaded. When I c ...

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

Leverage the pre-defined Ionic Sass variables for optimal styling

Is it possible to utilize existing Sass Variables in Ionic 5 for our custom CSS classes? The specific variables I am referring to can be found here: https://ionicframework.com/docs/v3/theming/overriding-ionic-variables/ I'm interested in creating som ...

What is the reason for the index type being defined twice?

Here is an example from the official TypeScript documentation: class Animal { name: string; } class Dog extends Animal { breed: string; } // Error: indexing with a 'string' will sometimes get you a Dog! interface NotOkay { [x: numbe ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

What is the best way to store a logged-in user's email in a React

I have implemented a login API and I would like to save the email of the logged-in user in the state or another variable, so that I can display it in the header after successful login. The user's email is located in the data.email. The following code ...

Can you guide me on utilizing the drag and drop functionality in Angular 8 CDK to merge two cards together?

My current challenge involves attempting to drag one card over another card in order to effectively "merge" or "combine" them, similar to the action of dragging an image onto a folder on a desktop. Despite utilizing HTML5 native drag and drop functionalit ...

NodeJS can be used to convert JSON data into an XLSX file format and allow for

I am currently working on a project in nodejs where I need to convert JSON data into XLSX format and then download it to the client's browser. I have been using the XLSX npm module to successfully convert the JSON data into a Workbook, however, I am f ...

The module declaration is triggering a lint error that reads "Unexpected token, expecting '{'"

To address the absence of available types for a library, I created the file omnivore.d.ts in TypeScript. Within this file, I added the following line: declare module '@mapbox/leaflet-omnivore' Upon running vue-cli-service lint in my project, an ...

The function angularCompiler.getNextProgram is not available in the context of angular 12 when using custom-webpack configurations

Recently, I upgraded my Angular 11 project to version 12. I have incorporated the @angular-builders/custom-webpack package in my devDependencies and I am using the below command for building my Angular project. ng build --configuration=production --build ...

Using the HTML form element to achieve two-way binding on array elements

I am working with an array of objects within a component that will be iterated in the template. app.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.compone ...

Is there a way to insert a record upon the user clicking on the Add Record button?

// Here is my Component code // I want to figure out how to add a new row to the table with fresh values. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-uom', templateUrl: './uom.component.html ...