-1

I have been stuck on this for a while. How would I loop over an object with array values. Please, any help with be appreciated. JSON data structures isn't my strong suite

var storeProducts = {"items": [
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/M997ST_6940.progressive.jpg?v=1497039024",
   "productname": "New Balance",
   "productlistprice": "$240",
   "discounted": "false",
   "productprice": "",
 },
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/Peacoat_363758_02_6428.progressive.jpg?v=1496428432",
   "productname": "Puma Sneakers",
   "productlistprice": "$120",
   "discounted": "false",
   "productprice": "",
 },
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/Titan_Weave_WhiteBlueEstate_50117182901_C6501_5945-78.progressive.jpg?v=1494616290",
   "productname": "Diadora",
   "productlistprice": "$100",
   "discounted": "true",
   "productprice": "190",
 },
]};
1
  • 2
    This seems like a very common question... are sure you looked for the answer? See for instance this or this... Commented Jun 25, 2017 at 23:32

2 Answers 2

1

@Arthur is right.

Solution:

foreach( var i = 0; i < storeProducts.items.length; i++ ) {
    var item = storeProducts.items[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

or even easier: storeProducts.items.forEach( item => console.log( item ) )
1

Let's say you want to grab all the imgsrc URLs. You can proceed like this.

let imgURL = storeProducts.items.map(product =>product.imgsrc);

To grab the first item in your array, you simply need to do.

let firstImgURL = imgURL[0];

let storeProducts = {
"items": [
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/M997ST_6940.progressive.jpg?v=1497039024",
   "productname": "New Balance",
   "productlistprice": "$240",
   "discounted": "false",
   "productprice": "",
 },
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/Peacoat_363758_02_6428.progressive.jpg?v=1496428432",
   "productname": "Puma Sneakers",
   "productlistprice": "$120",
   "discounted": "false",
   "productprice": "",
 },
 {
   "imgsrc": "https://cdn.shopify.com/s/files/1/0094/2252/products/Titan_Weave_WhiteBlueEstate_50117182901_C6501_5945-78.progressive.jpg?v=1494616290",
   "productname": "Diadora",
   "productlistprice": "$100",
   "discounted": "true",
   "productprice": "190",
 },
]};

var imgURL = storeProducts.items.map(product =>product.imgsrc);
console.log(imgURL);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.