如果你有这样的日期:
var t = {
"series1":[{'date1':4},{'date2':2},{'date3':6}],
"series2":[{'date1':5},{'date2':3}, {'date3':4},{'date4':6}],
"series3":[{'date2':1},{'date4':9}]
}
那么这应该工作:
var output = {};
function getKeys (obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
getKeys(t).forEach(function (val) {
t[val].forEach(function (ser) {
var date = getKeys(ser)[0];
if (!output.hasOwnProperty(date)) {
output[date] = [];
}
output[date].push(ser[date]);
});
});
console.log(output);
你会以这种格式得到它
Object {date1: Array[2], date2: Array[3], date3: Array[2], date4: Array[2]}
date1: Array[2]
date2: Array[3]
date3: Array[2]
date4: Array[2]
如果您想要这种格式的原始日期
var original = [
{"series1":[{'date1':4},{'date2':2},{'date3':6}]},
{"series2":[{'date1':5},{'date2':3},{'date3':4},{'date4':6}]},
{"series3":[{'date2':1},{'date4':9}]}
];
然后在getKeys
函数后面加上这个
var t = {},
output = {};
original.forEach(function (obj) {
var prop = getKeys(obj)[0];
if (! t.hasOwnProperty(prop) ) {
t[prop] = {}
}
t[prop] = obj[prop];
});