Search code examples
javascriptangulartypescriptangular-httpclient

Angular 2 json getting data objects


I got url which contains data arrays as json. I want to get and use all of the elements in it :

By doing this, i get everything and nothing specific. For example : How to get data.name or data.price.... ?

  ngOnInit() {
    this.http.get('this.url').subscribe(data => {
      console.log(data);

    })

Solution

  • You need to use array.find if you want to get the particular object name or price

     this.http.get('this.url').subscribe((data : any) => {
           let price = data.find(t=>t.name ==='yourName').price;
     });
    

    if its just an Object, you could access using the property,

    ngOnInit() {
        this.http.get('this.url').subscribe((data:any) => {
          console.log(data.name);
    })