我是jQuery和JSON的新手。我希望你能帮我完成我的小任务。我有以下JSON对象结构:jQuery - 如何从嵌套的JSON获取JSON数组名称
{
"recipe": {
"myREAL":0,
"mySTRING":"STRING variable",
"myUDINT":0,
"mybool":0,
"ingNumber":[0,0,0,0,0],
"ingMinimumWeight":[0,0,0,0,0],
"ingNominalWeight":[0,0,0,0,0]
}
}
我想获取数组名称的名称,而不是只获取索引和索引的值。
我到目前为止输出:
Key: myREAL Value: 0
Key: mySTRING Value: STRING variable
Key: myUDINT Value: 0
Key: mybool Value: 0
Key: 0 Value: 0
Key: 1 Value: 0
Key: 2 Value: 0
Key: 3 Value: 0
Key: 4 Value: 0
...
我感兴趣的是这样的结构:
Key: myREAL Value: 0
Key: mySTRING Value: STRING variable
Key: myUDINT Value: 0
Key: mybool Value: 0
ingNumber:
Key: 0 Value: 0
Key: 1 Value: 0
Key: 2 Value: 0
Key: 3 Value: 0
Key: 4 Value: 0
ingMinimumWeight:
...
我想这样做jQuery中没有specifiying数组变量的名称。
我的jQuery代码:
function iter(obj) {
for (var key in obj) {
if (typeof (obj[key]) == 'object') {
iter(obj[key]);
} else {
content = " Key: " + key + " Value: " + obj[key] + '\n';
var box = $("#myArea");
box.val(box.val() + content);
}
}
}
究竟是什么你想实现什么? – undefined 2015-03-03 13:55:41
我想给动态数组输出一个标题。正如你可以在我的JSON对象中看到的数组名是ingNumber,ingMinimumWeight ...如果我没有指定标题,我只会得到Key = number,Value = number,一路。它在控制台上看起来不太好。每次遇到一个数组,我都希望它首先打印数组的名称,然后打印出键和值。 – user3000138 2015-03-03 14:00:50
@ user3000138你只需要在对象内包含box.val(),如果条件如此:) – mohamedrias 2015-03-03 14:17:19