简体   繁体   中英

How to convert JSON array from REST API to an object

From my backend I receive message like this:

[
    [
        {
            "id": 1,
            "date": "2018-12-31"
        },
        {
            "id": 12,
            "standard": null,
            "capacity": 7,
            "description": null,
        }
    ],
    [
        {
            "id": 26,
            "date": "2018-12-08"
        },
        {
            "id": 11,
            "standard": null,
            "capacity": 7,
            "description": null,
        }
    ]
]

I want to map this response to list of 2 objects, so I created class:

export class Response {

  id: string;
  date: string;
  standard: string;
  capacity: number;
  description: string;
}

I my method, where I calling a service I tried different methods, and even backendData.forEach doesn't work - Angular doesn't recognize backendData as an array.

getData(){
    this.service.getData().subscribe(backendData=>{
      //how to convert  backendData to an array of Response[]?
    })
  }

I will be very grateful for every help I have been stuck with this for couple of time.

Maybe it helps

getData(){
    this.service.getData().subscribe(backendData=> {
        //how to convert  backendData to an array of Response[]?
        return backendData.map(array => Object.assign(array[0], array[1]))
    })
}

I'm not sure that you really can convert to Response type this array, because your id is string, but in response you got number, also you got nullable description and standard in response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM