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

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Consolidating repeated data objects found in the response

After receiving an API response, the data looks like this: response = [ { id: 1, val: 'A', date: '28/03/2021', versions: [] }, { id: 1, val: 'B', date: '29/03/2021', versions: [] }, { id: 1, val: 'C', ...

What is the process for waiting on RxJS data and how should it be retrieved?

I am faced with a situation where I need to create a user through a function, but before proceeding with the creation process, I have to verify whether another user with the same userName is already present in the session: public createUser(form: FormGroup ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

What might be causing my observable to fail to return a value?

I'm currently utilizing an API known as ngx-pwa localstorage, which serves as a wrapper for an indexeddb database. Within my Angular project, I have a service that interacts with this database through a method called getItem: getItem(key: string) { ...

Angular5 encountered a problem with the ngx-bootstrap DatePicker when handling DateTime objects

I currently have a SQL Server database field called 'JoiningDate' with the type of date (no time included). To collect input from users, I am utilizing the ngx-bootstrap datepicker. However, I am encountering an issue where the datepicker convert ...

What are the essential Angular 2 observables for me to utilize?

I have created a form input for conducting searches. Upon user input into the search bar, I want to trigger calls to two separate APIs simultaneously. Here is my current attempt: myInput: new FormControl(); listOne: Observable<string[]>; listTwo: Ob ...

Encountering an "ionic 4 frame-ancestors *" error while attempting to watch a Twitter video

Currently, I am in the process of developing a news app using Ionic 4. I recently tackled the challenge of embedding tweets in Twitter cards successfully. However, a new issue has arisen. When a tweet includes a Youtube video, everything works perfectly ac ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

What is the significance of requiring a specific string in a Typescript Record when it is combined with a primitive type in a union?

I am facing an issue with the following data type: type ErrorMessages = Record<number | 'default', string>; When I declare a variable like const text: ErrorMessages = {403: 'forbidden'}, Typescript points out that default is miss ...

What is the method for referencing a subtype within an established type?

When working with React-native, I came across a component called FlatList which includes a property known as ListHeaderComponent. My question is how to specify the type of this property without having to manually copy and paste the original type. Currentl ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

What is the method for adding attributes to a class dynamically in TypeScript so that they can be accessed by instances?

I attempted to create a universal factory function that generates custom enum objects, but the instances were not able to retrieve the correct properties. Take a look at the preview of the code online: https://stackblitz.com/edit/typescript-rkl1zr Workin ...

Angular 2 keypress validation: Ensuring data integrity through real-time input verification

I am currently facing an issue with implementing number validation in my Angular2 project. I am struggling to replicate the JavaScript code provided below. Here is the HTML: <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyp ...

Setting the default sorting order of a Primeng table based on the value of an observable

When using a p-table with sortable columns, I encounter an issue where I want the table to be sorted by a specific column initially. However, the column is not known until run-time so I utilize sortField for that purpose. Here's a portion of the table ...

Utilize cypress to analyze the loading time of a webpage

My current challenge involves using cypress to carry out website tests. I am looking for a reliable method to measure the duration it takes for certain cypress commands to load or execute. As an example: //var startTime = SomeStopwatchFunction(); cy.visit( ...

encountering difficulties with implementing the custom pagination feature in Angular 2

After creating a custom pagination component using Angular2, I encountered an error when trying to use it in another component: Can't bind to 'offset' since it isn't a known property of 'app-pagination'. Update Made in app. ...

How can I access a DOM element in an AngularJS 2 TypeScript file?

As a newcomer to AngularJS, I am attempting to add a spinner as a background to all images on my website. Since there are multiple images, using a single variable like isLoaded in the TypeScript file is not feasible. Here is how I am implementing it in th ...