如何把oldData数据形式转为newData形式的数据
const oldData = {
1: { 苹果: [{ weight: 1 }] },
2: { 橘子: [{ weight: 1 }] },
3: { 苹果: [{ weight: 1.2 }] },
4: { 苹果: [{ weight: 3 }] },
5: { 苹果: [{ weight: 4 }, { weight: 1 },{ weight: 1 }], 香蕉: [{ weight: 6 }, { weight: 4}] },
6: { 香蕉: [{ weight: 3.2 }] },
}
const newData={
max:4,
data:{
1:[{x:0,num:1,type:'苹果'}],
2:[{x:0,num:1,type:'橘子'}],
3:[{x:0,num:1.2,type:'苹果'}],
4:[{x:0,num:3,type:'苹果'}],
5:[{x:0,num:4,type:'苹果'},{x:4,num:1,type:'苹果'},{x:5,num:1,type:'苹果'},{x:6,num:6,type:'香蕉'},{x:12,num:4,type:'香蕉'}],
6:[{x:0,num:3.2,type:'香蕉'}],
}
}
for。。in遍历oldData,在一层for..in遍历一次oldData里面的项,最后for ..of遍历数组项压入newData中,示例如下
不过max
怎么算出来4
的?应该是6
吧,所有项中的weight最大值。
const oldData = {
1: { 苹果: [{ weight: 1 }] },
2: { 橘子: [{ weight: 1 }] },
3: { 苹果: [{ weight: 1.2 }] },
4: { 苹果: [{ weight: 3 }] },
5: { 苹果: [{ weight: 4 }, { weight: 1 }, { weight: 1 }], 香蕉: [{ weight: 6 }, { weight: 4 }] },
6: { 香蕉: [{ weight: 3.2 }] },
}
const newData = { max: 0, data:{ }}
for (let item in oldData) {
newData.data[item] = []
var x = 0;
for (var attr in oldData[item]) {
for (var value of oldData[item][attr]) {
newData.max = Math.max(newData.max, value.weight);
newData.data[item].push({ x: x, num: value.weight, type: attr })
x += value.weight;
}
}
}
console.log(newData)
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!