简体   繁体   中英

build multi-dimensional array in javascript

Im retrieving a Json dataset and need to build a javascript array called 'arrProducts'. My code below is wrong but on the right lines. Can anybody help??

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;           
    });     
});

This should do what you want:

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 is already in the format you are trying to build, so you should really just use data.products directly.

var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json",
function(data) {
    console.log(data.products);
});
    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.

You just have to create an array using this code:

var arrProducts = [];

The rest of your code will serve your purpose

But, as the comment states, this will create a three elements associative array which will be overwrittenin each iterarion. You need to re-think your structure: multidimensioanl array? array of objects?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM