我正在检索 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;
});
});
最佳答案
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
});
});
正如 Kevin B 指出的那样,看起来 data.products 已经是您要采用的格式的对象数组,因此这种“转换”似乎毫无意义。
关于javascript - 在javascript中构建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123672/