The best way to convert Array to JSON in typescript with example

You can also check other posts on Javascript Add,Delete from Array

Casting Array and JSON introduction

The frontend will interact with the Database in Typescript apps like Angular using REST API. REST API is a separate application that communicates with a database and can be created in any language. The REST API accepts JSON as input and returns JSON as output.

Angular applications which are based on the MVC pattern take the input from the View layer and store/holds them in an array of objects as a model in a Controller.

We have various use cases in the Angular application, as follows:

  • Add/Update data

    The user inputs data into the user interface, which is received by the controller as an Array of the object as a model, which is an input REST API. We’ll have to `convert this Array of objects to JSON objects as a result.

  • Read Data from Database

    The angular application consumes REST API data. This data is in the format of JSON format and it needs to convert to Array of Objects to display it in the User interface. When you are dealing with Data from REST API, We will write angular Services to manipulate data. Services are a delegation of the request between the Controller and Data layer.

You are about to learn How to convert Array to JSON and JSON to Array in typescript for example.

Before Doing conversion, Always understands the Structure of JSON, and applies logic as per JSON structure.

typescript is an extended version of javascript.

Below examples works on javascript environment also.

How to Convert Array of Objects to JSON with examples

There are many ways You can convert Array to JSON

  • forEach loop Following are step by step guides using for each Loop

  • Created Array and initialize it with initial data where each object contains id and name values.

  • Create a temporary object using the let keyword for holding data.

  • forEach() method in the array is used to iterate the array of elements in the same order. This has a callback function that called for every element.

  • Using lambda expression, Loop through each element and add the element to a temporary object.

  • Finally, JSON.stringify() method is used to convert Object to JSON string

let empArray = [
  {
    id: "1",
    name: "kiran",
  },
  {
    id: "2",
    name: "john",
  },
  {
    id: "3",
    name: "Frank",
  },
];

let jsonObject = {};
empArray.forEach((item) => (obj[item.id] = item.name));
let json = JSON.stringify(jsonObject);
console.log(empArray);
console.log(json);

Output:

0: {id: "1", name: "kiran"}
1: {id: "2", name: "john"}
2: {id: "3", name: "Frank"}
{"1":"kiran","2":"john","3":"Frank"}

  • Using ES6 spread Operator ES6 introduced Spread Operator and Object assign method to process array.

  • First called `array map() method’ is called a function for every element during the iteration and returns a new array for each element.

  • This new array contains index=0 as id: “1” and index=1 as name: “kiran”

  • Create an Object with these values in the map chain to return a new array,

  • Next, step deep copy the array of objects to new objects.

  • Convert this object to JSON string using JSON.stringify() method_.

Here is an example code

let jsonObject = Object.assign(
  ...empArray
    .map((key) => Object.values(key))
    .map((value) => ({ [value[0]]: value[1] })),
);
let json = JSON.stringify(jsonObject);
console.log(empArray);
console.log(json);

Output is the same for this code.

How to Convert JSON to Array Objects

  • Created JSON object and Empty Array Object
  • using for...in the loop, Iterated each element of the JSON object.
  • Add each element to the Array using the push method
let jsonObject = {
  1: "kiran",
  2: "john",
  3: "Frank",
};

var outputArray = [];
for (let element in jsonObject) {
  outputArray.push({
    id: element,
    name: jsonObject[element],
  });
}
console.log(outputArray);

Output:


0: {id: "1", name: "kiran"}
1: {id: "2", name: "john"}
2: {id: "3", name: "Frank"}

Conclusion

You learned Array and JSOn in typescript.

  • Convert Array to JSOn
  • Parse JSon to Array