如何在jQuery中的foreach内部有一个foreach?
-
11-10-2019 - |
题
大家好!首先,我知道这种东西很糟糕,但这就是我可视化实现目标的方式。
这是一个交易:我有一个包含数组的JSON对象,但是不幸的是,我必须迭代一个JSON对象的列表,然后遍历以前截断的数组。 JSON对象看起来如下(在葡萄牙语中,但你们可以理解):
{“ produtos”:[{“ key”:“ derivados de ferro”,“ value”:217816909},{“ key”:“ Madeiras,suas manufaturas eMobiliárioMebiliárioMédicoCirúrgico”,“值“:“ celulose,papel e suas obras”,“ value”:100086937},{“ key”:“ carnesuína”,“ value”:81738783},{“ key”:“ carne bovina” },{“ key”:“ carne de aves”,“ value”:65292433},{“ key”:“ untros”,“ value”:4444520811}],“ ano”:2005,“ tipo”:1}
Produtos是我提到的数组,我还有其他两个重要的值:ANO(年)和Tipo(类型)。我的代码如下:
jQuery.getJSON("/webportos/Porto/GraficoComercio?id=" + iddoporto.className + "&ano=2005", null, function (items) {
jQuery.each(items, function (itemNo, item) {
jQuery.each(item.produtos, function (dicNo, dic) {
options.series.push({ name: dic.Key, data: dic.Value});
options.title.text = "Comércio - "+item.ano;
options.yAxis.title.text = "Exportação";
options.tooltip.formatter = function () {
return '<b><u>' + this.series.name + '</u></b><br/><b>' + this.x + '</b>: ' + this.y + ' ';
}
});
});
chart = new Highcharts.Chart(options);
});
该代码使Chrome JavaScript控制台显示:
ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:32 Uncaught TypeError: Cannot read property 'length' of undefined
你们能帮我吗?
解决方案
这是因为您想在非数组上使用.east()吗?
jQuery.each(items, function (itemNo, item) {
从我的理解来看,jQuery.east(对象,回调,args)仅用于数组。它要做的第一件事是调用对象。所以除非你有
[{“ produtos”:[{“ key”:“ derivados de ferro”,“ value”:217816909},{“ key”:“ Madeiras,suas manufaturas eMobiliárioMebiliárioMédicoCirúrgico”,“值“:“ celulose,papel e suas obras”,“ value”:100086937},{“ key”:“ carnesuína”,“ value”:81738783},{“ key”:“ carne bovina” },{“ key”:“ carne de aves”,“ value”:65292433},{“ key”:“ untros”,“ value”:4444520811}],“ ano”:2005,“ tipo”:1}]
你会得到这个错误。
此外,您可能会考虑二极管的建议。 jquery.east的性能要比仅使用for loop循环数据要低得多。
其他提示
您不需要jQuery通过JSON数据进行迭代。使用普通的旧JavaScript。
看到这个问题: 在HTML中显示JSON/YAML层次结构?
function renderJSON(obj) {
var keys = []
var retValue = ""
for (var key in obj) {
if(typeof obj[key] == 'object') {
retValue += "<div class='tree'>" + key
retValue += renderJSON(obj[key])
retValue += "</div>"
}
else {
retValue += "<div class='tree'>" + key + " = " + obj[key] + "</div>"
}
keys.push(key)
}
return retValue
}