0

我很难访问特定的 json 数据。这是我的 json 文件

{
  "id": "72",
  "title": "Item Category Product Level Average Price Comparison",
  "xLabel": null,
  "yLabel": "Average Price",
  "zLabel": null,
  "data": [{
      "avgPrice": "87",

      "numProducts": "85"
    }, {
      "avgPrice": "60",

      "numProducts": "49"
    }, {
      "avgPrice": "59",

      "numProducts": "65"
    }

我想先取商家名称对应的唯一值的 avgPrice 和 numProducts 的值。例如,在 json 数据中,第一个和最后一个商家名称相同(即“商家名称”:“A”)。所以我想先取商家A的价值,然后再取商家B的价值(如果重复我想先完成那个,然后再去另一个商家。

var mn = [];
$.each(returnedData.data, function (index, value) {
  if($.inArray(value.merchantName, mn) == -1) {
    mn.push(value.merchantName);
  }
});
 //all the merchants name stored in mn[]

function get_items_by_merchant(merchant_name) {
  var items = new Array();
  $.each(returnedData.data, function (index, item) {
    if(returnedData.merchantName == merchant_name)
      items.push(item);
  });
  return items;
}
var CB_items = [];
for(var i = 0; i < mn.length; i++) {
  CB_items[i] = get_items_by_merchant(mn[i]);
  $.each(CB_items, function (index, item) {
    var avgpricve = parseFloat(response.data[i].avgPrice);
    var numproducts = parseFloat(response.data[i].numProducts);
    datajson = {
      x: avgpricve,
      y: numproducts
    }
    result_data.push(datajson)
  });
}

响应是 json 文件中的数据,我使用 $.getJSON 获取它。在上面的代码中,我想

访问商家名称行 response.data[i].mn[i].avgPrice.. 既然我无法.. 有什么办法可以吗?

4

1 回答 1

1

在函数中get_items_by_merchant改变这个

$.each(returnedData.data, function(index, item) {
                if (returnedData.merchantName == merchant_name) // There is not merchantName in returnedData.
                    items.push(item);
   });

 $.each(returnedData.data, function(index, item) {
            if (item.merchantName == merchant_name)
                items.push(item);
        });

最终代码更改:-

演示

var result_data = [];
var mn = [];
$.each(returnedData.data, function (index, value) {
    if ($.inArray(value.merchantName, mn) == -1) {
        mn.push(value.merchantName);
    }
});
//all the merchants name stored in mn[]

function get_items_by_merchant(merchant_name) {
    var items = new Array();
    $.each(returnedData.data, function (index, item) {
        if (item.merchantName == merchant_name) items.push(item);
    });
    return items;
}
var CB_items = [];
for (var i = 0; i < mn.length; i++) {

    CB_items[i] = get_items_by_merchant(mn[i]);
    $.each(CB_items[i], function (index, item) {
        var avgpricve = parseFloat(item.avgPrice);
        var numproducts = parseFloat(item.numProducts);
        datajson = {
            x: avgpricve,
            y: numproducts
        }
        result_data.push(datajson)
    });
    console.log(result_data)
于 2013-05-12T06:05:00.227 回答