The behavior of the dynamically generated object array differs from that of a fixed test object array

I'm facing an issue while trying to convert JSON data into an Excel sheet using the 'xlsx' library. Everything works perfectly when I use test data:

//outputs excel file correctly with data

var excelData = [{ test: 'test', test2: "yes" }, { test: 'testingAgain', test2: "no" }];
this.excelService.exportJSON(excelData, "test2");

However, when I try to create my own array of objects with dynamic properties, it doesn't work as expected. Even though the static test object and the dynamically generated object appear identical during debugging, the resulting Excel file ends up empty.

//outputs empty file even though object Array is a valid object containing valid data with object keys.

var objectArray = [];
dataDocs.forEach(doc => {
    let obj = {};
    obj["test"] = "test";
    obj["test2"] = "yes";
    objectArray.push(obj);
}
this.excelService.exportJSON(objectArray , "test3");

This is my Excel service:

 export class ExcelService {

  private EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
  private EXCEL_EXTENSION = '.xlsx';

  constructor() { }

  exportJSON(jsonData: any, fileName) {
    let worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData);
    let workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    let excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

    return this.generateExcelFile(excelBuffer, fileName);
  }
  private generateExcelFile(buffer: any, fileName: string) {
    let data: Blob = new Blob([buffer], {
      type: this.EXCEL_TYPE
    });
    return FileSaver.saveAs(data, fileName + this.EXCEL_EXTENSION)
  }
}

https://i.sstatic.net/keWqo.jpg

I'd really appreciate any assistance. The above code snippet highlights the issue I am encountering. While initializing an object array with fixed objects and properties works fine with Excel, dynamically generating objects and pushing them to the array causes the export to fail (even though both arrays are valid).

(the top object array doesn't work, the bottom object array works)

Answer №1

Seems like the dataDocs array is empty. To fix this, you can add a condition to check if there is data in dataDocs before running the foreach statement:

var objectArray = [];
if (dataDocs && dataDocs.length > 0) {
    dataDocs.forEach(doc => {
        let obj = {};
        obj["test"] = "test";
        obj["test2"] = "yes";
        objectArray.push(obj);
    }
}
this.excelService.exportJSON(objectArray , "test3");

UPDATE:

You should also check if objectArray has data before calling the exportJson method:

if (objectArray && objectArray.length > 0) {
    this.excelService.exportJSON(objectArray , "test3");
}

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

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...

Tips for managing nested data in Angular 4 using a Bootstrap 4 data-table

I am currently using the Data Table from a GitHub project found at: https://github.com/afermon/angular-4-data-table-bootstrap-4-demo. It works perfectly with data structured in a key-value format like the sample provided. However, I am facing challenges wh ...

Tips for accessing data in Angular 2

When utilizing the post method, the following code is used in the ts file: viewt(testid) { $('#myModal22').modal('show'); var param2 = { testid:testid, } this.service.get_tquestion(param2).subscribe(data => { ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

What could be the reason for the lack of impact when assigning a [dateClass] in mat-calendar?

I've been trying to customize the appearance of specific days in the mat-calendar component from Angular Material, but I'm having trouble getting it to work. I discovered the dateClass property which seemed like the right solution, but no matter ...

Angular Leaflet area selection feature

Having an issue with the leaflet-area-select plugin in my Angular9 project. Whenever I try to call this.map.selectArea, VSCode gives me an error saying that property 'selectArea' does not exist on type 'Map'. How can I resolve this? I& ...

Highchart in ionic 2 not displaying

I inserted code for a highchart on my webpage, but it's not appearing I followed instructions from this video tutorial https://www.youtube.com/watch?v=FSg8n5_uaWs Can anyone help me troubleshoot this issue? This is the TypeScript code I used: ts; ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Include bootstrap CSS files on specific Angular 6 pages

Currently, I am utilizing angular 6 and Bootstrap CSS by including the CSS link in my index.html. <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <width=device="initial-scale=1"> <base href="/"> & ...

Next.js typescript tutorial on controlling values with increment and decrement buttons

I'm just starting to learn typescript and I'm looking to implement increment and decrement buttons in a next.js project that's using typescript. export default function Home() { return ( <div className={styles.container}> ...

Tips for accessing the return value from a method outside of its containing function

Having recently started using Angular, I'm encountering an issue with retrieving a return value from a function that I have implemented within another one. private validateKeyterm(): boolean { const val = this.form.value.term; if ...

Utilizing NPM Workspaces to efficiently distribute TypeScript definition files (`*.d.ts`) across multiple workspaces

In my TypeScript monorepo utilizing NPM Workspaces, I have two packages: A and B. Package B requires type definitions from package A. To accomplish this, I included a reference to A's definition file in the tsconfig.json of package B. However, somet ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Error TS2309: TypeScript encountered an error in Types/node/index.d.ts

I recently upgraded my .Net Core Angular 2 project using SystemJs from Typings to @Types. The entire project has been rebuilt with the latest VS tooling for .Net Core 1.0.1, TypeScript 2.0.10, and Node.js 7.0.0 as of 12/21/2016. Everything was working fi ...

Issue with host-context scss rules not appearing in final production version

I am facing an issue in my Angular project where the scss rules that define how components should look when within the context of another component are not being applied when I build for production and put it live. Here is an example: :host-context(my-tabl ...

Setting an attribute on a custom component that is dynamically created within an Angular application

I am working with a custom library component called <my-icon>. To display the icon, I need to specify the property [name] like this: <my-icon [name]='warning'></my-icon> Currently, I am dynamically creating these icons in Type ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

Shifting the use of @Inject(MAT_DIALOG_DATA) away from class constructors

Our team is making a transition in the Dependency Injection pattern we utilize to minimize the dependency on TypeScript constructors. This shift will help us address recurring issues caused by team members adding logic that shouldn't be included in co ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...