我正在尝试将Javascript对象文字转换为另一个。我认为有些循环是可能的,但我无法完成。目标结构如下所示:“convertedData”。
小提琴可以在这里找到:http://jsbin.com/ajemih/9/edit
这是JSON数据:
var data =
{
"29-10-2012": {
"1a": {
"allMovement": "1",
"allLoad": "2",
"loadMovement": "3"
},
"1b": {
"allMovement": 4,
"allLoad": 5,
"loadMovement": 6
}
},
"22-02-2013": {
"1a": {
"allMovement": "7",
"allLoad": "8",
"loadMovement": "9"
},
"1b": {
"allMovement": "10",
"allLoad": "11",
"loadMovement": "12"
}
}
};
for (day in data) {
for (id in data[day]) {
document.write(data[day][id].allMovement+"<br>");
document.write(data[day][id].allLoad+"<br>");
document.write(data[day][id].loadMovement+"<br>");
}
}
/*
convertedData = [[1,7],
[2, 8],
[3, 9],
["4","10"],
["5","11"],
["6", "12"]];
convertedData = [["1a-allMovement-29-10-2012","1a-allMovement-22-02-2013],
["1a-allLoad-29-10-2012", "1a-allLoad22-02-2013"],
["1a-loadMovement-29-10-2012", "1a-loadMovement-22-02-2013"],
["1b-allMovement-29-10-2012","1a-allMovement-22-02-2013"],
["1b-allLoad-29-10-2012","1b-allLoad22-02-2013"],
["1b-loadMovement-29-10-2012", "1b-loadMovement-22-02-2013"]];
*/
最佳答案
这是使用jQuery.each()函数的解决方案:
var convertedObj = {};
$.each(data, function(i0,val0) {
$.each(val0, function(i1,val1) {
$.each(val1, function(i2,val2) {
if (!convertedObj[i1+"-"+i2]) convertedObj[i1+"-"+i2] = [];
convertedObj[i1+"-"+i2].push(val2);
});
});
});
var convertedData = [];
$.each(convertedObj, function(i,val) {
convertedData.push(val);
});
这是link to a jsbin fiddle
(在控制台中查看结果)