4 回答
TA贡献1805条经验 获得超10个赞
const obj = {
"date": {"0": "20180201", "1": "20180202", "2": "20180205"},
"lines": {"0": 3.3, "1": 10.4, "2": 79.721},
"count": {"0": 5, "1": 21, "2": 13},
"counts": {"0": 5, "1": 26, "2": 39},
"limit": {"0": 3.3, "1": 13.7, "2": 93.421}
};
const keys = Object.keys(obj);
const lens = Object.keys(obj[keys[0]]);
let arrays = []
for (const len of lens) {
let o = {};
for (const key of keys) {
o[key] = obj[key][len];
}
arrays.push(o);
}
console.log(arrays);
结果:
[ { date: '20180201', lines: 3.3, count: 5, counts: 5, limit: 3.3 },
{ date: '20180202',
lines: 10.4,
count: 21,
counts: 26,
limit: 13.7 },
{ date: '20180205',
lines: 79.721,
count: 13,
counts: 39,
limit: 93.421 } ]
新需求:
const obj = {
"v_date": {"0": "20180201", "1": "20180202", "2": "20180205", "3": "20180206", "4": "20180207", "5": "20180208"},
"type": {"0": "现券交易", "1": "现券交易", "2": "质押式回购", "3": "质押式回购", "4": "质押式回购", "5": "现券交易"},
"amt": {"0": 3.3, "1": 10.4, "2": 79.721, "3": 68.363, "4": 25.674, "5": 12.1},
"num": {"0": 5, "1": 21, "2": 13, "3": 21, "4": 18, "5": 32},
"sum_num": {"0": 5, "1": 26, "2": 13, "3": 34, "4": 52, "5": 58},
"sum_amt": {"0": 3.3, "1": 13.7, "2": 79.721, "3": 148.084, "4": 173.758, "5": 25.8}
};
const keys = Object.keys(obj);
const lens = Object.keys(obj.type);
let types = {};
for (const t of lens) {
if(!types[obj.type[t]]) {
types[obj.type[t]] = [];
}
let o = {};
for (const key of keys) {
if (key !== 'type') {
o[key] = obj[key][t]
}
}
types[obj.type[t]].push(o);
}
console.log(types)
结果:
{ '现券交易':
[ { v_date: '20180201', amt: 3.3, num: 5, sum_num: 5, sum_amt: 3.3 },
{ v_date: '20180202',
amt: 10.4,
num: 21,
sum_num: 26,
sum_amt: 13.7 },
{ v_date: '20180208',
amt: 12.1,
num: 32,
sum_num: 58,
sum_amt: 25.8 } ],
'质押式回购':
[ { v_date: '20180205',
amt: 79.721,
num: 13,
sum_num: 13,
sum_amt: 79.721 },
{ v_date: '20180206',
amt: 68.363,
num: 21,
sum_num: 34,
sum_amt: 148.084 },
{ v_date: '20180207',
amt: 25.674,
num: 18,
sum_num: 52,
sum_amt: 173.758 } ] }
当你执行console.log(Object.values(types))的时候,你会发现更多的惊喜
TA贡献1798条经验 获得超3个赞
source为你最开始那个对象
for(var i =0,len=3;i<len;i++){
values[i].date=source['date'][i];
values[i].lines=source['lines'][i];
...
}
TA贡献1829条经验 获得超4个赞
const oData = {
"date":{"0":"20180201","1":"20180202","2":"20180205"},
"lines":{"0":3.3,"1":10.4,"2":79.721},
"count":{"0":5,"1":21,"2":13},
"counts":{"0":5,"1":26,"2":39},
"limit":{"0":3.3,"1":13.7,"2":93.421}
},
fnData = function(o, l, a = [], i = 0) {
for (let k in oData) {
if (!a[i]) a[i] = {};
a[i][k] = o[k][i];
}
return ++i < l && fnData(o, l, a, i) || a;
};
alert(JSON.stringify(fnData(oData, 3)));
添加回答
举报