How to print specific data attribute in JSON response object

Sk Koralagoda Source

How to print specific data attribute in JSON response

I get respose like this.

ionViewDidLoad() {
  
    console.log('ionViewDidLoad SonglistPage');
    this.eid = this.backendprovider.getEventID();
    console.log('eventID');
    console.log(this.eid);
    this.backendprovider.sendEventID(this.eid).subscribe((songs) => {
      this.songslist = songs;
      
    });

  }

I want to print the title of songs object. please help me. Thanks

This is what I tried. But it prints all the object data

 const myObjStr = JSON.stringify(songs);
 console.log(myObjStr);

Print Output:

[{"id":{"timestamp":1518586352,"machineIdentifier":3380871,"processIdentifier":5056,"counter":16748217,"time":1518586352000,"date":1518586352000,"timeSecond":1518586352},"songId":1,"title":"Somebody's Me","artist":"Enrique Iglesias","genre":"Jazz"}]

javascriptapiionic-frameworkvisual-studio-code

Answers

answered 6 months ago Taher Khorshidi #1

use map finction:

const songTitles = songs.map(a=>a.title);
console.log(JSON.stringify(songTitles));

answered 6 months ago Adrian Farmadin #2

songs variable is an array. You need to iterate the array to get song titles.

ionViewDidLoad() {
  
    console.log('ionViewDidLoad SonglistPage');
    this.eid = this.backendprovider.getEventID();
    console.log('eventID');
    console.log(this.eid);
    this.backendprovider.sendEventID(this.eid).subscribe((songs) => {
      this.songslist = songs;
      songs.forEach((song) => {
        console.log(song.title);
      });
    });

  }

Foreach documentation.

answered 6 months ago Nemanja #3

If you use ajax and jQuery to get the response then you can do something like this:

$.ajax(function()
{
url:'your endpoint url',
data: function(d){

//your data
   }
success: function(response){

var songTittle = response['title'];
console.log(songTittle);//should print Somebody's Me
       }
error: function(response)
{
//error callback
}

});

But generally speaking, something like this response['tittle'] should do the work

answered 6 months ago Mebin Varghese #4

it's array result you can print it using *ngFor

<div *ngFor = "let song of songslist">
{{song.title}}
</div>

comments powered by Disqus