人到中年有點(diǎn)甜
2019-02-27 10:11:45
const customer = [ {id: 1, count: 2}, {id: 2, count: 89}, {id: 3, count: 1}];轉(zhuǎn)換成:const customer = [ {type:'id',value:[1,2,3]}, {type:'count',value:[2,89,1]},];//customer是動(dòng)態(tài)數(shù)據(jù),id和count并不是固定的解決方案可參考sxlwar回答內(nèi)他的評(píng)論。
1 回答

呼啦一陣風(fēng)
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
const middle = customer.reduce((acc, cur) => {
Object.keys(cur).forEach(key => {
if(acc[key]){
acc[key].push(cur[key]);
}else {
acc[key] = [cur[key]];
}
});
return acc;
},{});
const r = Object.keys(middle).map(key => ({type: key, value: middle[key]}));
// or
const result = Object.keys(middle).reduce((acc,cur) => {
acc.push({type: cur, value: middle[cur]});
return acc;
}, []);
添加回答
舉報(bào)
0/150
提交
取消