Wednesday, August 21, 2019

Export JSON to CSV file in angular

In this Article, we will learn How to convert an JSON array in to CSV and How to Export CSV as a downloadable file by using Blob in angular 8.



Image credits to blog.derakkilgo.com

If you are interested to see the demo click https://stackblitz.com/edit/angular8-json-to-csv
Last week, While I was working on my angular project, I got a new requirement from our client, The requirement is exporting the existing table data in to a csv file.
For this requirement, I have created a new service where I am converting my JSON data in to CSV first, then exporting the CSV file using blob.
Step1:- Converting JSON to CSV
For converting JSON data in to CSV format use the follwing method.
ConvertToCSV(objArray, headerList) {
 let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
 let str = '';
 let row = 'S.No,';
 for (let index in headerList) {
  row += headerList[index] + ',';
 }
 row = row.slice(0, -1);
 str += row + '\r\n';
 for (let i = 0; i < array.length; i++) {
  let line = (i+1)+'';
  for (let index in headerList) {
   let head = headerList[index];
   line += ',' + array[i][head];
  }
  str += line + '\r\n';
 }
 return str;
}
The first parameter is Array of Objects, and second parameter is the headers List generally the keys of Json.
Step2:- Exporting CSV as a downloadable file.
For exporting CSV data as a .csv file use the follwing method.
downloadFile(data, filename='data') {
        let csvData = this.ConvertToCSV(data, ['name','age', 'average', 'approved', 'description']);
        console.log(csvData)
        let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
        let dwldLink = document.createElement("a");
        let url = URL.createObjectURL(blob);
        let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
        if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
            dwldLink.setAttribute("target", "_blank");
        }
        dwldLink.setAttribute("href", url);
        dwldLink.setAttribute("download", filename + ".csv");
        dwldLink.style.visibility = "hidden";
        document.body.appendChild(dwldLink);
        dwldLink.click();
        document.body.removeChild(dwldLink);
}

The download method accepts two parameters, the first parameter in JSONdata and the second parameter is filename. the default file name here is data. In the downloadFile method we are calling ConvertToCSV method which converts the JSON to CSV.
Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. you can read more about blob from https://developer.mozilla.org/en-US/docs/Web/API/Blob
app.service.ts:- Create a new service file with name app.component.ts
import { Injectable } from '@angular/core';
@Injectable()
export class AppService {
downloadFile(data, filename='data') {
        let csvData = this.ConvertToCSV(data, ['name','age', 'average', 'approved', 'description']);
        console.log(csvData)
        let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
        let dwldLink = document.createElement("a");
        let url = URL.createObjectURL(blob);
        let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
            dwldLink.setAttribute("target", "_blank");
        }
        dwldLink.setAttribute("href", url);
        dwldLink.setAttribute("download", filename + ".csv");
        dwldLink.style.visibility = "hidden";
        document.body.appendChild(dwldLink);
        dwldLink.click();
        document.body.removeChild(dwldLink);
    }
ConvertToCSV(objArray, headerList) {
         let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
         let str = '';
         let row = 'S.No,';
for (let index in headerList) {
             row += headerList[index] + ',';
         }
         row = row.slice(0, -1);
         str += row + '\r\n';
         for (let i = 0; i < array.length; i++) {
             let line = (i+1)+'';
             for (let index in headerList) {
                let head = headerList[index];
line += ',' + array[i][head];
             }
             str += line + '\r\n';
         }
         return str;
     }
}
Now we have our service file, use this sevice file in our component to send the data and check whether our downloadFile method is properly working or not. before creating component, first import our service in app.module.ts
app.module.ts:-
import { AppService } from './app.service';
@NgModule({
  providers: [AppService],
})
app.component.ts:-
import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
constructor(private appService:AppService) {  }
jsonData =  [
      {
        name: "Anil Singh",
        age: 33,
        average: 98,
        approved: true,
        description: "I am active blogger and Author."
      },
      {
        name: 'Reena Singh',
        age: 28,
        average: 99,
        approved: true,
        description: "I am active HR."
      },
      {
        name: 'Aradhya',
        age: 4,
        average: 99,
        approved: true,
        description: "I am engle."
      },
    ];
download(){
    this.appService.downloadFile(this.jsonData, 'jsontocsv');
  }
}
and finally, our app.component.html file
<h1>Convert Json to CSV file and Download it in the .csv format</h1><button (click)="download()"> Download </button>
That’s it, Now run your angular application and click on download button which is going to create a new csv file.

Summary

We have learned How to convert an JSON array in to CSV and How to Export CSV as a downloadable file by using Blob.

Tuesday, August 20, 2019

Different ways(7 ways) of creating an Object in JavaScript

In this article, we will learn different ways to create objects in JavaScript like object literal, using the new keyword, Object.create() method, constructor function, ES6 Class and Singleton Pattern.

1. Object Literal Way

The Simplest and easiest way to create an object is using Object Literal “{}”. Just define properties and values inside curly braces as follows.
let person = { name : “Hello” }

where name is the property of person object and Hello is the value of the name property.
Properties of an Object can be accessed by a dot notation or by bracket notation as follows.
console.log(person.name) // Output: Hello
       or
console.log(person[‘name’]) // Output: Hello

2. new Object() Way

Another simplest way to create an Object is by using new Object().
let person = new Object({name : “Hello” });
Creating objects using new Object() and object literal does the same thing. For simplicity, readability and execution speed, use object literal way.

3. Object.create() Way

Basic syntax of the Object.create() is as follows.
Object.create(PrototypeObject, PropertiesObject)
The object.create method accepts two arguments.
  1. Prototype Object: Newly created objects prototype object. It has to be an object or null.
  2. Properties Object: Properties of the new object. This argument is optional
let person = Object.create(null);
person.name = "Sachin";
console.log(person); // { name : "Sachin" }

4. Constructor Function Way

The constructor is just a function and constructor function allows to create multiple objects of the same function with the help of new keyword as shown below.
function Vehicle(name, type) {
   this.name = name;
   this.type= type;
}
let vehicle1 = new Vehicle(’Ford’, 'Car’);
let vehicle2 = new Vehicle(’KTM’, 'Bike’);
console.log(vehicle1.name);    //Output: Ford
console.log(vehicle2.name);    //Output: KTM

Using the function constructor with prototype:

function Vehicle() {
}
Vehicle.prototype.name = "Ford";Vehicle.prototype.type = "Car";
let vehicle1 = new Vehicle();
console.log(vehicle1.name);    //Output: Ford

5. ES6 Classes Way

Es6 supports Classes concept. By using classes we can create a new object as shown below.
class Vehicle {
  constructor(name, maker) {
    this.name = name;
    this.maker =  maker;
  }
}
let vehicle1 = new Vehicle(’Ford’, 'Car’);
let vehicle2 = new Vehicle(’KTM’, 'Bike’);
console.log(vehicle1.name);    //Output: Ford
console.log(vehicle2.name);    //Output: KTM

6. Factory Function Way

We can also create an Object using the factory function way as shown below.
function person(name, age) {
   return { name, age };
}
let person1 = person(‘Bunny’, 24);
console.log(person1.name); // Output: Bunny
console.log(person1.age); // Output: 24

7. Singleton Pattern

The word Singleton itself says that a singleton object Ensure a class has only one instance and provide a global point of access to it.
let person = new function() {
   this.name = "Bunny";
}
console.log(person.name); // Output: Bunny

Summary

We have learned about different possible ways to create a new object in JavaScript.