0

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.

1 Answer 1

1

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

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

Comments

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.