如何将JSON数组转换为JavaScript 2D数组[duplicate]

时间:2021-04-03 21:36:29

This question already has an answer here:

这个问题已经有了答案:

I want to convert the following JSON into a JS 2D array, but I am not sure how to do this in html.

我想将下面的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}]

The result should be something like:

结果应该是:

[[23.0, 'WEST END'], [14.0, 'MOUNT PLEASANT']]

Thank you so much!

谢谢你这么多!

2 个解决方案

#1


1  

This will work with all fields of "fields", not only for diameter or neighborhood.

这将适用于“字段”的所有字段,不仅适用于直径或邻域。

Demo:

演示:

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));

#2


0  

For each item in json push a new array with the diameter and neighborhood into a result array.

对于json中的每个项目,将具有直径和邻域的新数组推入结果数组。

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);

#1


1  

This will work with all fields of "fields", not only for diameter or neighborhood.

这将适用于“字段”的所有字段,不仅适用于直径或邻域。

Demo:

演示:

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));

#2


0  

For each item in json push a new array with the diameter and neighborhood into a result array.

对于json中的每个项目,将具有直径和邻域的新数组推入结果数组。

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);