原始数据
const data = [{ id: 1, spec: '规格1', rules: [{ rank: 10, breaks: 100 }, { rank: 50, breaks: 10 }, { rank: 100, breaks: 5 } ] }, { id: 2, spec: '规格2', rules: [{ rank: 10, breaks: 200 }, { rank: 50, breaks: 20 }, { rank: 100, breaks: 25 } ] } ];
使用 forEach 遍历
function skuFormat(data) { let RankList = []; data.forEach(item => { item.rules.forEach(ite => { if (RankList.indexOf(ite.rank) === -1) RankList.push(ite.rank); }) }) let newData = []; RankList.forEach(item => { newData.push({ rank: item, skus:[] }) }) newData.forEach(item=>{ data.forEach(ite=>{ let Remark={ id:ite.id, spec:ite.spec, breaks:0 } try { ite.rules.forEach(it=>{ if(item.rank===it.rank){ Remark.breaks=it.breaks; item.skus.push(Remark); throw(new Error('find item')); } }) } catch (error) { } }) }) return newData; } let newData= skuFormat(data); console.log(newData)
使用 reduce 处理
let newData=data.reduce((pre, cur) => { console.log(cur,pre) const list = cur.rules.map(item => ({ rank: item.rank, skus: [{ id: cur.id, spec: cur.spec, breaks: item.breaks }] })) if (!pre.length) { return list; } return pre.map((item, key) => { return { ...item, skus: [...item.skus, ...list[key].skus] } }) }, []); console.log(newData)