malachi54 malachi54 - 6 months ago 233
Javascript Question

convert a JSON to a string array in typescript

I feel like I have quite an easy question but I just don't get to the answer...
I parse the .text() of a response from my server with JSON.parse into JSON.
And i actually can access the values of that JSON with:

this.temp[0].name
.
Now i just want to iterate over that JSON and push the values into a string array. But how can i achieve this?

When i attempt to use
for...of
the compiler wants a string or an array but not a JSON. When i attempt to use
for...in
it actually does not go into the loop.

Here is some code where i can access it fine:

this._pS.getAllProjects()
.subscribe(data => this.temp = JSON.parse(data.text()),
err => console.log(err),
() => console.log("hello " + this.temp[0].name + this.temp[1].name));


When i just print it out after .stringify():

this._pS.getAllProjects()
.subscribe(data => this.temp = JSON.stringify(data),
err => console.log(err),
() => console.log("hello " + this.temp));


i get this in the browser console:

{"_body":"[{\"name\":\"Projekt A\"},{\"name\":\"Projekt XYZ\"}]",
"status":200,
"ok":true,
"statusText":"Ok",
"headers":{"Content-Type":["application/json; charset=utf-8"]},
"type":2,
"url":"http://127.0.0.1:3000/api/getAllProjectNames"}


tl;dr: how can i get the values out of text part of the body into a string array?

Thanks in advance

Answer

If the response is what you included then it's simple:

JSON.parse(data.text()).forEach(item => {
    console.log(item.name);
});

As your body is an array of objects of this interface:

interface ObjectInResponseArray {
    name: string;
}