Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

js如何转换如下数据?

需求:把数据res整成validRes,循环了半天还是没整理出来,各位大佬们,请问该如何转换?谢谢 ~

    createdate: '2020-04-09', 
    data: 'xxxxx1' 
},{ 
    createdate: '2018-08-24', 
    data: 'xxxxx2' 
},{ 
    createdate: '2020-04-23', 
    data: 'xxxxx3'
}
let validRes = [{ 
    year: '2020', 
    data: [{   
        month: '4', 
        data: [{ 
            day: '04-09', 
            data 'xxxxx1' 
       },{ 
            day: '04-23', 
            data: 'xxxxx3' 
       }]
   }] 
},{ 
   year: '2018', 
   data: [{ 
        month: '8', 
        data: [{ 
            day: '08-24', 
            data: 'xxxxx2' 
       }] 
   }] 
}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const source = [{
    createdate: '2020-04-09',
    data: 'xxxxx1'
}, {
    createdate: '2018-08-24',
    data: 'xxxxx2'
}, {
    createdate: '2020-04-23',
    data: 'xxxxx3'
}, {
    createdate: '2020-05-23',
    data: 'xxxxx3'
}];
const obj = {};

source.map(value => {
    const splitDate = value.createdate.split('-');
    const year = splitDate[0];
    const month = `${parseInt(splitDate[1])}`;
    const day = value.createdate.replace(new RegExp(`${splitDate[0]}-`), '');

    if (!obj[year]) {
        obj[year] = {
            year,
            data: {}
        }
    }
    if (!obj[year].data[month]) {
        obj[year].data[month] = {
            month,
            data: []
        }
    }

    obj[year].data[month].data.push({
        day,
        data: value.data
    });
});

for (const key in obj) {
    obj[key].data = Object.values(obj[key].data);
}
console.log(Object.values(obj));

这是我想到的最简洁的代码


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...