0

I have an array of JSON and want to paste it into an array variable in typescript.

the JSON I receive from http://www.example.com/select.php:

{ 
     "User":[ 
      {"Name":"Luca M","ID":"1"},
      {"Name":"Tim S","ID":"2"},
      {"Name":"Lucas W","ID":"3"} 
     ] 
    }

I would like to get an array like that:

  this.items = [
          'Luca M',
          'Tim S',
          'Lucas W'
        ];

EDIT:

current code is

 this.http.post('http://www.example.com/select.php', creds, {
          headers: headers
      })
          .map(res => res.json().User) 

          .subscribe(
          data => this.data = data.User.map(user => user.Name), 
          err => this.logError(err),
          () => console.log('Completed')
          );


      this.items = this.data;

error:

Cannot read property 'map' of undefined

how can I realize this?

Thanks and best regards

1 Answer 1

2

For this very specific json:

const json = {
    "User": [
        { "Name": "Luca M", "ID": "1" },
        { "Name": "Tim S", "ID": "2" },
        { "Name": "Lucas W", "ID": "3" } 
    ] 
}

const items = json.User.map(user => user.Name);
console.log(items); // ["Luca M", "Tim S", "Lucas W"]

(code in playground)

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your suggestion, I forgot to mention, that I receive my JSON from an API. Could you help me once more according to my Edit?
I tried const json = JSON.stringify(this.data); this.items = this.data.map(user => user.Name); but this did not work as I expected
You don't need to stringify your data, if you do that you end up with a string and not an object...
Alright, makes sense, but it does not work either this.items = this.data.map(User => User.Name); --Cannot read property 'map' of undefined
You're probably doing an asynchronous operation. You need to wait until that is finished. Do that part in the subscribe callback: data => this.data = data.User.map(user => user.Name)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.