user2828442
user2828442

Reputation: 2515

How to fetch json result in array using Ionic 2?

I am fetching data from JSON api using the below code in my 'listproduct.ts'

names = [];

this._listProduct.listProduct().subscribe(data => {
  this.list = data;
 console.log(data);
 });

In console.log, I am fetching the result as expected, attaching a picture for your reference:

enter image description here

I need to fetch data.NAME in names array, how can I do this ?

data.NAME is not working.

Upvotes: 0

Views: 66

Answers (1)

Sunny Pun
Sunny Pun

Reputation: 726

As from the console, data is an array (of 10 elements).

When we want to convert an array to another array of the same size, 1-to-1 with some kind of "mapping", we can use the map() function.

Replace console.log(data); with this line names = data.map( e => e.NAME );

Check if it works ;)

Explanation

The function map() takes a function to be its argument, and one of the usages is to specify the element (e here) and how it corresponds to the result you want (we want e.NAME instead of the whole object e).

So e => e.NAME is a short form of e => { return e.NAME; } you may modify the function body as you might need in the future.

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Upvotes: 1

Related Questions