我想从数组创建一个 JSON 树。 我的数组是这样形成的:
var arraySource = [];
arraySource.push({key : "fr", value: "france"});
arraySource.push({key : "es", value: "spain"});
//...
console.debug(arraySource);
我想制作一个像这样形成的json树
var destJson = {
"fr" : "france",
"es" : "spain"
};
我不知道如何动态地做到这一点,因为要做到这一点我必须这样做
destJson.fr = "france"
但这是不可能的,因为数组中的项目是动态的
有什么想法吗? 如果你想玩我做了一个jsfiddle:
最佳答案
如果 JavaScript 中存在动态键,则有 square bracket notation :
$.each(arraySource, function(index, item) {
destJson[item.key] = item.value;
});
关于javascript - 构建动态 json 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909670/