Aviral Goyal
Aviral Goyal

Reputation: 45

Map Observable from JSON to array

I am receiving JSON Data from an api and I need to map it to separate arrays.

Data is being received in this format:

[
  {"MONTH":9,"YEAR":2015,"SUMAMT":0},
  {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5},
  {"MONTH":11,"YEAR":2015,"SUMAMT":539252}
]

and I need to convert it to

Array1 = [Sep-2015,Oct-2015,Nov-2015]
Array2 = [0,11446.5,539252]

This is the code I am trying, but I'm not sure how to implement it.

This is the service receiving the data:


    getSalesTrend(): Observable < any > {
      return this.http.get<any>(`${this.apiPath}/salesTrend`)
        .pipe(
          map(data => {
            this.date = new Date(data.YEAR, data.MONTH, 1);
            return this.date.formatDate(this.date, "MMM-YYYY");
          })
        )
    }

This is the component subscribing to the data:

salesTrendData: any[]
ngOnInit() {
    this.adminService.getSalesTrend()
      .subscribe(salesTrendData => {
        this.salesTrendData = salesTrendData
        console.log(this.salesTrendData);
      })
  }

console.log should give me: Array1 and Array2

Any help would be greatly appreciated. I'm fairly new to this forum, please let me know if you need more information and thanks in advance :)

Upvotes: 0

Views: 750

Answers (1)

wentjun
wentjun

Reputation: 42516

First, you will need an object to map the month values. Then, you use Array.map() to achieve the desired results, as shown in the demo below.

const months = {
   '1': 'Jan',
    '2':'Feb',
    '3':'Mar',
    '4':'Apr',
    '5':'May',
    '6':'Jun',
    '7':'Jul',
    '8':'Aug',
    '9':'Sep',
    '10':'Oct',
    '11':'Nov',
    '13':'Dec'
}

const data = [{"MONTH":9,"YEAR":2015,"SUMAMT":0}, {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5},{"MONTH":11,"YEAR":2015,"SUMAMT":539252}];

const Array1 = data.map(obj => {
  const month = months[obj.MONTH]
  return `${month}-${obj.YEAR}`;
})

const Array2 = data.map(obj => obj.SUMAMT)
console.log(Array1);
console.log(Array2);

Here is how we can integrate that into your code. After carrying out the mapping, we still store both of them into an object, and then return the object to your component.

getSalesTrend(): Observable<any> {
  return this.http.get<any>(`${this.apiPath}/salesTrend`)
    .pipe(
      map(data => {
        const months = {'1': 'Jan', '2':'Feb', '3':'Mar', '4':'Apr', '5':'May', '6':'Jun', '7':'Jul', '8':'Aug', '9':'Sep', '10':'Oct', '11':'Nov', '13':'Dec'};
        const Array1 = data.map(obj => {
          const month = months[obj.MONTH]
          return `${month}-${obj.YEAR}`;
        });
        const Array2 = data.map(obj => obj.SUMAMT);
        return {Array1, Array2};
      })
    )
  }
}

Upvotes: 1

Related Questions