循环遍历json / array / object

时间:2017-06-25 23:28:49

标签: javascript arrays json sorting object

我被困在这一段时间了。我如何在具有数组值的对象上循环。请,任何帮助,不胜感激。 JSON数据结构不是我强大的套件

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",
 },
]};

2 个答案:

答案 0 :(得分:1)

@Arthur是对的。

解决方案:

foreach( var i = 0; i < storeProducts.items.length; i++ ) {
    var item = storeProducts.items[i];
}

答案 1 :(得分:1)

我们假设您要抓取所有imgsrc网址。你可以这样继续。

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

要获取数组中的第一项,您只需要这样做。

let firstImgURL = imgURL[0];

&#13;
&#13;
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);
&#13;
&#13;
&#13;