Mike
Mike

Reputation: 25

Javascript loop ignore array index

I am attempting to loop over product data where each node of data is in its own index of the array. How can I return all "product-name" or "product-url" values regardless of their index?

My code looks like this

var products = res.data.CO;

products.forEach((product, index) => {
    console.log(product);
});

I am able to return each entry but not able to use dot or bracket notation to only bring back one value from each entry. Any help is much appreciated.

Here is my data https://i.sstatic.net/Zn5oL.png

Upvotes: 1

Views: 458

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370759

Use .map to transform one array into another:

const productNames = products.map(product => product['product-name']);

Upvotes: 1

ug_
ug_

Reputation: 11440

You can access values using an array like bracket notation

var products = res.data.CO;

products.forEach((product, index) => {
    console.log(product['product-name']);
});

Or if you just want the product names you could do reduce

s using an array like bracket notation

var products = res.data.CO;

// array of product names
products.map(product => product['product-name']);

Upvotes: 0

Related Questions