How to append additional field in the existing REST API JSON in typescript

Issue

I want to add additional column which is not exist in my original response. I’m calling multiple REST endpoints one by one, and combining all the results into single JSON and showing in the Angular Mat table. I want to display these columns – ['postId', 'id', 'name', 'email', 'body', 'environment'];

I’m getting value for all columns except environment, this is something I want to add once I get the response from REST API.

For example, when I call onGetPost('post-1'), I want to add this field "environment": "dev" in the existing response. This is the original response I get when I call this api – https://jsonplaceholder.typicode.com/posts/1/comments

[
{
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi"
  },
{
    "postId": 1,
    "id": 2,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi"
  }
]

I want to modify the response like below:

[
{
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi",
     "environment": "dev"
  },
{
    "postId": 1,
    "id": 2,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi",
     "environment": "dev"
  }
]

Likewise, when it calls onGetPost('post-2'), this field should get appended "environment": "qa" in all the items, onGetPost('post-3') should be "environment": "uat" and onGetPost('post-4') should be "environment": "prod".

I tried below code but this is not working as expected:

        if (postId == 'post-1') {
            response.forEach(obj => {
                Object.entries(obj).forEach(([key, value]) => {
                    //console.log(`${key} ${value}`);
                    this.item[key] = value;
                    this.item['environment'] = 'dev';
                });
                this.my_array.push(this.item)
            }); 
        }

Please find my complete code snippet:

post.component.ts

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { PostService } from './post-service';
import { Post } from './post';

export class PostComponent implements OnInit {


    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

    post: Post[];
    dataSource;
    columnsToDisplay = ['postId', 'id', 'name', 'email', 'body', 'environment'];
    my_array = [];
    item = {};

    /**
     * Constructor
     */
    constructor(
        private postService: PostService,
        private _liveAnnouncer: LiveAnnouncer,
        private cdr: ChangeDetectorRef) { }

    listPost() {
        this.onGetPost('post-1');
        this.onGetPost('post-2');
        this.onGetPost('post-3');
        this.onGetPost('post-4');
    }

    onGetPost(postId): void {
        this.postService.getPost(postId).subscribe(
            (response) => {
                console.log(response);
                this.my_array.push(...response)
            if (postId == 'post-1') {
                response.forEach(obj => {
                    Object.entries(obj).forEach(([key, value]) => {
                        //console.log(`${key} ${value}`);
                        this.item[key] = value;
                        this.item['environment'] = 'dev';
                    });
                    this.my_array.push(this.item)
                }); 
            }
                this.dataSource = new MatTableDataSource(this.my_array.push);
                this.cdr.detectChanges();
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;
            },
            (error: any) => {
                console.log('entering into error block')
                console.log(error)
                this.dataSource = new MatTableDataSource();
                this.cdr.detectChanges();
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;

            },
            () => console.log('Done getting all post')
        );
    }

    filterData($event: any) {
        this.dataSource.filter = $event.target.value;
    }
    announceSortChange(sortState: Sort) {
        if (sortState.direction) {
            this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
        } else {
            this._liveAnnouncer.announce('Sorting cleared');
        }
    }

    /**
     * On init
     */
    ngOnInit(): void {
        this.listPost();

    }

}

post-service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Post } from "./post";

@Injectable({ providedIn: 'root' })
export class PostService {

    constructor(private http: HttpClient) { }
    endpoint: any;
    getPost(id): Observable<Post[]> {

        console.log(id);
        switch (id) {
            case 'post-1':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/1/comments';
                break;
            case 'post-2':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/2/comments';
                break;
            case 'post-3':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/3/comments';
                break;
            case 'post-4':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/4/comments';
                break;
        }
        return this.http.get<Post[]>(this.endpoint);
    }
}

Could you please help me to resolve this issue.
Appreciated your support on this. Thanks!

Final output should look like below:

[
    {
        "postId": 1,
        "id": 1,
        "name": "id labore ex et quam laborum",
        "email": "Eliseo@gardner.biz",
        "body": "laudantium enim quasi est",
        "environment": "dev"
    },
    {
        "postId": 1,
        "id": 2,
        "name": "quo vero reiciendis velit similique earum",
        "email": "Jayne_Kuhic@sydney.com",
        "body": "laudantium enim quasi est",
        "environment": "dev"
    },
    {
        "postId": 1,
        "id": 3,
        "name": "odio adipisci rerum aut animi",
        "email": "Nikita@garfield.biz",
        "body": "laudantium enim quasi est",
        "environment": "dev"
    },
    {
        "postId": 2,
        "id": 6,
        "name": "et fugit eligendi deleniti quidem qui sint nihil autem",
        "email": "Presley.Mueller@myrl.com",
        "body": "laudantium enim quasi est",
        "environment": "qa"
    },
    {
        "postId": 2,
        "id": 7,
        "name": "repellat consequatur praesentium vel minus molestias voluptatum",
        "email": "Dallas@ole.me",
        "body": "laudantium enim quasi est",
        "environment": "qa"
    },
    {
        "postId": 2,
        "id": 8,
        "name": "et omnis dolorem",
        "email": "Mallory_Kunze@marie.org",
        "body": "laudantium enim quasi est",
        "environment": "qa"
    },
    {
        "postId": 3,
        "id": 9,
        "name": "provident id voluptas",
        "email": "Meghan_Littel@rene.us",
        "body": "laudantium enim quasi est",
        "environment": "uat"
    },
    {
        "postId": 4,
        "id": 10,
        "name": "eaque et deleniti atque tenetur ut quo ut",
        "email": "Carmen_Keeling@caroline.name",
        "body": "laudantium enim quasi est",
        "environment": "prod"
    }
]

Solution

Hello All you need to use the javascript map function to modify the array of objects

const ob = [
{
   "postId": 1,
   "id": 1,
   "name": "id labore ex et quam laborum",
   "email": "Eliseo@gardner.biz",
   "body": "laudantium enim quasi"
},
{
   "postId": 1,
   "id": 2,
   "name": "id labore ex et quam laborum",
   "email": "Eliseo@gardner.biz",
   "body": "laudantium enim quasi"
}
]
const mapped = ob.map((i)=> {
    i['environment'] = "dev" // add your condition for qa/dev etc (post == 1) ? dev : qa etc
    return i;
});
console.log(mapped)

Answered By – Pardeep

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.