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'

}]

}]

}]

回答

function extend(data) {

let res = {};

for (let i = 0; i < data.length; i++) {

let date = data[i].createdate.split('-');

if (!res[date[0]]) {

res[date[0]] = {};

res[date[0]][date[1]] = [{

day: `${date[1]}${date[2]}`,

data: data[i].data

}]

} else if (!res[date[0]][date[1]]) {

res[date[0]][date[1]] = [{

day: `${date[1]}${date[2]}`,

data: data[i].data

}]

} else {

res[date[0]][date[1]].push({

day: `${date[1]}${date[2]}`,

data: data[i].data

})

}

}

console.log(res);

}

提供下思路

image.png

以上是 js如何转换如下数据? 的全部内容, 来源链接: utcz.com/a/40395.html

回到顶部