我有这个简单的JSON数组结构
[
[ "1000", "Kangar","Perlis" ],
[ "1532", "Kangar", "Perlis" ],
[ "2000", "Kuala Perlis", "Perlis" ],
[ "6250", "Alor Setar", "Kedah" ],
[ "6300", "Kuala Nerang", "Kedah" ]
]
现在我想像这样构造JSON
{
"Perlis":
{
"Kangar": [ "1000", "1532" ],
"Kuala Perlis": [ "2000" ]
},
"Kedah":
{
"Alor Setar":["6250"],
"Kuala Nerang":["2000"]
}
}
那么如何使用Javascript对象达到此结果呢?
最佳答案
尝试跟随
var arr = [
["1000", "Kangar", "Perlis"],
["1532", "Kangar", "Perlis"],
["2000", "Kuala Perlis", "Perlis"],
["6250", "Alor Setar", "Kedah"],
["6300", "Kuala Nerang", "Kedah"]
];
var obj = {};
arr.forEach(function(item) {
obj[item[2]] = obj[item[2]] || {};
obj[item[2]][item[1]] = obj[item[2]][item[1]] || [];
obj[item[2]][item[1]].push(item[0]);
});
console.log(obj);
关于javascript - Javascript:将JSON数组转换为级联JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42528141/