我尝试创建从我的数据库返回的动态JSON whith数据: 我想要的是:
var myJSON = {
"value" : [ {
"icon_name": "value",
"factor_name": "value",
"number": "value",
"priority": "value"
},
{
"icon_name": "value",
"factor_name": "value",
"number": "value",
"priority": "value"
} ],
"value" : [ {
"icon_name": "value",
"factor_name": "value",
"number": "value",
"priority": "value"
},
{
"icon_name": "value",
"factor_name": "value",
"number": "value",
"priority": "value"
} ],
...
};
每个"值"是动态的,依赖于我的sql响应。我的sql响应看起来像这样。
[ RowDataPacket {
row_names: 587,
icon_name: 'small_event',
factor_name: 'Petit évènement',
number: 10,
priority: 1 },
RowDataPacket {
row_names: 587,
icon_name: 'cold',
factor_name: 'Température basse',
number: 10,
priority: 7 },
RowDataPacket {
row_names: 587,
icon_name: 'rain',
factor_name: 'Pluie',
number: 10,
priority: 12 },
RowDataPacket {
row_names: 588,
icon_name: 'small_event',
factor_name: 'Petit évènement',
number: 10,
priority: 1 },
RowDataPacket {
row_names: 588,
icon_name: 'cold',
factor_name: 'Température basse',
number: 10,
priority: 7 }]
一个row_names有几个值(icon_name,factor_name,...)。我想为每个唯一的row_names重新组合所有这些值。
这里我的代码(rows [3]是我的sql输出):
var result = []
var r_names = "";
var j = 0;
var id = "";
for(i = 0; i < rows[3].length; i++) {
if(r_names != rows[3][i].row_names) {
j = 0;
id = ''+rows[3][i].row_names;
result[id] = [];
r_names = rows[3][i].row_names
}
result[id].push({});
result[id][j]["icon_name"] = rows[3][i].icon_name,
result[id][j]["factor_name"] = rows[3][i].factor_name,
result[id][j]["number"] = rows[3][i].number,
result[id][j]["priority"] = rows[3][i].priority
j++;
}
这是我的结果:
...
,
,
,
,
,
,
,
,
,
,
,
[ { icon_name: 'small_event',
factor_name: 'Petit évènement',
number: 10,
priority: 1 },
{ icon_name: 'temperate',
factor_name: 'Température modéré',
number: 10,
priority: 7 },
{ icon_name: 'rain',
factor_name: 'Pluie',
number: 10,
priority: 12 } ],
,
,
,
,
,
,
...
,
,
,
,
,
,
[ { icon_name: 'small_event',
factor_name: 'Petit évènement',
number: 10,
priority: 1 },
{ icon_name: 'temperate',
factor_name: 'Température modéré',
number: 10,
priority: 7 },
{ icon_name: 'rain',
factor_name: 'Pluie',
number: 10,
priority: 12 } ] ]
我不知道为什么我有这么多&#39;。我没有成功找到我的错误。 你知道吗?
答案 0 :(得分:3)
问题是,您将row_names
的值作为数组的索引,并且位于start 587
。使用该索引,您将生成一个稀疏数组。
id = ''+rows[3][i].row_names;
result[id] = [];
为了防止这种情况,你可以使用一个对象,然后你可以使用row_names
的值作为结果的关键。
var result = {};