0

我正在检索一个 Json 数据集,需要构建一个名为“arrProducts”的 javascript 数组。我下面的代码是错误的,但在正确的行上。有人可以帮忙吗??

var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    var productsArray = data.products;
    var arrProducts = '';
    $.each(productsArray, function(index, product) {
        arrProducts['name'] = product.name;                        
        arrProducts['title'] = product.title;
        arrProducts['price'] = product.price;           
    });     
});
4

4 回答 4

1
    var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    var productsArray = data.products;
    var arrProducts = []; //This needs to be an array not a string.
    $.each(productsArray, function(index, product) {
        var prod = {};//make a new product for each iteration
        prod['name'] = product.name;                        
        prod['title'] = product.title;
        prod['price'] = product.price;    
        arrProducts.push(prod); //add the product to thearray of products       
    });     
});

As Kevin B points out, it looks like data.products is already an array of objects in the format you are going to, so this "conversion" seems pointless.

于 2012-10-29T14:41:05.993 回答
1

这应该做你想要的:

var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    var productsArray = data.products;
    var arrProducts = productsArray;
});

productsArray已经是您尝试构建的格式,因此您应该data.products直接使用。

var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    console.log(data.products);
});
于 2012-10-29T14:38:10.317 回答
0

How about this ?

var arr;
var allProducts = $.getJSON("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    arr = jQuery.makeArray(data);
});

Note :

You need to use getJSON method so that your end up with an already Parsed Object that you then can use in the callback. As for makeArray method http://api.jquery.com/jQuery.makeArray/

于 2012-10-29T14:41:37.097 回答
0

您只需使用以下代码创建一个数组:

var arrProducts = [];

您的其余代码将服务于您的目的

但是,正如评论所述,这将创建一个三元素关联数组,该数组将在每个迭代中被覆盖。你需要重新考虑你的结构:multidimensioanl array?对象数组?

于 2012-10-29T14:36:56.857 回答