How to get json data in array in ionic?


#1

Hi. I am new in ionic-2. I need to get json data using http request and store the data in array. below is the sample json data.

{
    "data": [
        {
            "id": 4,
            "date": "2016-11-17",
            "product": "Lillium",
            "product_id": 3,
            "product_type": "Flower",
            "quantity_produced": 200,
            "created": 1495591050
        },
        {
            "id": 5,
            "date": "2016-12-06",
            "product": "Gerbera",
            "product_id": 1,
            "product_type": "Flower",
            "quantity_produced": 300,
            "created": 1495591067
        }
    ]
}

from the above json data, i need to store only “quantity_produced” values in array.
for eg: [ 200, 300, 500, 110, 220 ]. please suggest any solution. thank you.


#2

I’m sorry with your post I have no idea where your issue is. If you don’t know how the get data via http
follow the guide from Joshua

if you don’t know how to store data, then please read first the Angular2 guides.
https://angular.io/

hope it helps.


#3

I think a quick & simple way to do it would be :

 var json;

 this.http.get('link/to/your/api').map(res => res.json()).subscribe(data => {
        json = data;
    });

and then parse it in this way

var qp = []
for (var i of json.data) {
 qp.push(i.quantity_produced);
}

Here is a link to the parse script

Hope this solves your problem. :slight_smile:


#4

thank you. your parse data technique was usefull. :blush: :innocent: @saidatta123


#5

Thanks a lot bro, you saved my day.
skydevelopers


#6

I don’t see what everybody else apparently does with regard to the post marked as the solution here. It has poorly-delineated spheres of control and a needless loop that could cause lots of unnecessary allocations. What I would do instead:

interface Product {
  id: number;
  date: string;
  // &c
}

interface ProductsResponse {
  data: Product[];
}

class Provider {
  constructor(private _http: HttpClient) {}
  allProducts(): Observable<Product[]> {
    return this._http.get<ProductsResponse>(url).pipe(
      map(prsp => prsp.data));

  onlyQuantities(): Observable<number[]> {
    return this.allProducts().pipe(
      map(prods => prods.map(prod => prod["quantity_produced"])));
  }
}

#7

Sorry rapropos, by the OP request an array of quantity_produced

So the pipe needs a mergeAll and a map to quantity_produced

:sunglasses:


#8

Heh. I’m skeptical about that, because it would be hard to do anything with those numbers devoid of context, but good catch. Added a onlyQuantities() method that delivers that.


#9

Yup. But lets see if the OP person will go for the more advanced and future proof solution in RXjs