When I make an ajax call that returns JSON data, my goal is to extract and organize this data into a new JavaScript array through looping.
This is a snippet of the JSON data returned:
{
query: [ ],
products:
[
{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http://www.zinio.com",
newsstand: "http://www.link1.php"
},
{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http://www.zinio.com",
newsstand: "http://www.link2.php"
},
{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http://www.zinio.com",
newsstand: "http://www.link3.php"
}
]
}
I'm struggling with how to properly loop through this JSON data in JavaScript. Here's what I have attempted so far, although it needs improvement as my JavaScript skills are not the strongest:
var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {
var arrProducts = [];
for (var i = 0; i < data.products.length; i++) {
var product = data.products[i];
var item = {
title: product.title,
url: product.url,
label: product.title,
magazine: product.magazine,
image: product.imageThumb,
newsstand: product.newsstand,
googleplay: product.googleplay,
kindle: product.kindle,
barnesnoble: product.barnesnoble,
zinio: product.zinio,
kobo: product.kobo,
waterstones: product.waterstones,
type: product.type,
brandurl: product.brandurl
};
arrProducts.push(item);
}
console.log(arrProducts);
});