我想将以下JSON转换为JS 2D数组,但我不知道如何在html中执行此操作。
[{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345},
{"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}]
结果应该是这样的:
[[23.0, 'WEST END'], [14.0, 'MOUNT PLEASANT']]
非常感谢你!
答案 0 :(得分:1)
这适用于“字段”的所有字段,不仅适用于diameter
或neighborhood
。
<强>演示强>:
var items = [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}];
var i = 0, result = [];
while(i < items.length){
result.push([])
for(var key in items[i].fields){
result[result.length-1].push(items[i].fields[key])
}
i++
}
document.write(JSON.stringify(result, null, 4));
答案 1 :(得分:0)
对于json
中的每个项目,将diameter
和neighborhood
的新数组推送到结果数组中。
var json = [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}];
var done = [];
json.forEach(function(object){
done.push([object.fields.diameter,object.fields.neighbourhood]);
});
console.log(done);