我试图以下列方式更新现有的json对象,而不使用普通java脚本中的任何函数。这是在一次采访中提出的。
附件是我的输入文件:
{
"height_c": 534,
"width_c": "800",
"height_h": 1067,
"width_h": "1600",
"height_k": 1366,
"width_k": "2048",
"height_l": "683",
"width_l": "1024",
"height_m": "333",
"width_m": "500",
"height_n": 213,
"width_n": "320",
"height_q": "150",
"width_q": "150",
"height_s": "160",
"width_s": "240",
"height_sq": 75,
"width_sq": 75,
"height_t": "67",
"width_t": "100",
"height_z": "427",
"width_z": "640"
}
附件是我的预期文件:
{
"sizes": {
"c": {
"width": 800,
"height": 534
},
"h": {
"width": 1600,
"height": 1067
},
"k": {
"width": 2048,
"height": 1366
},
"l": {
"width": 1024,
"height": 683
},
"m": {
"width": 500,
"height": 333
},
"n": {
"width": 320,
"height": 213
},
"q": {
"width": 150,
"height": 150
},
"s": {
"width": 240,
"height": 160
},
"q": {
"width": 75,
"height": 75
},
"t": {
"width": 100,
"height": 67
},
"z": {
"width": 640,
"height": 427
}
}
}
任何帮助都将不胜感激。我正在寻找一个起点。
答案 0 :(得分:1)
var input = {
"height_c": 534,
"width_c": "800",
"height_h": 1067,
"width_h": "1600",
"height_k": 1366,
"width_k": "2048",
"height_l": "683",
"width_l": "1024",
"height_m": "333",
"width_m": "500",
"height_n": 213,
"width_n": "320",
"height_q": "150",
"width_q": "150",
"height_s": "160",
"width_s": "240",
"height_sq": 75,
"width_sq": 75,
"height_t": "67",
"width_t": "100",
"height_z": "427",
"width_z": "640"
}
var output = {}
for (var key in input) {
var split = key.split('_')
if (!output[split[1]]) output[split[1]] = {};
output[split[1]][split[0]] = input[key];
}
document.body.appendChild(document.createTextNode(JSON.stringify({sizes: output}, null, 4)));

body { white-space: pre; font-family: monospace; }