Takács Roland
Takács Roland

Reputation: 1

How to convert an array response to json in Angular?

If I send an HTTP GET request to an API, I get an array as a response:

For example: [[Peter, 22, 1990], [Dan, 33, 2000]].

How can I convert it to JSON?

I want this instead of the array:

[{"Name":"Peter,"Age":22, "Born":1990}, {"Name":"Dan","Age":33, "Born":2000}]

Upvotes: 0

Views: 446

Answers (1)

nicowernli
nicowernli

Reputation: 3348

You will have to define your fields manually because Typescript can't guess which field will be the name, or which one will be the age for instance. But if you define the fields, you could do something like this.

const data = [['Peter', 22, 1990], ['Dan', 33, 2000]];
const json = data.map(([name, age, year]) => ({ name, age, year }));

BTW, this has nothing to do with Angular itself, this is a pure javascript question.

Upvotes: 2

Related Questions