gpt4 book ai didi

javascript - 将数组数据转换为对象

转载 作者:行者123 更新时间:2023-11-28 11:43:11 24 4
gpt4 key购买 nike

所以我有这个数组。

["2020-01-31 18:31:01", "2020-02-03 14:04:30", "2020-02-04 05:58:48", "2020-02-04 14:11:16"]

我喜欢将其转换为对象。

0: {date: "2020-01-31", time: ["8:31:01"]}
1: {date: "2020-02-03", time: ["4:04:30"]}
2: {date: "2020-02-04", time: ["5:58:48", "14:11:16"]}

但是我得到了这个结果

0: {date: "2020-01-31", time: "8:31:01"}
1: {date: "2020-02-03", time: "4:04:30"}
2: {date: "2020-02-04", time: "5:58:48"}

这是我的代码

var times = response.data.time;
var dates = [];
var t = [];
var d = '';
var newData = [];
times.forEach(time => {

var da = time.substring(0, 10);
var ti = time.substring(12, 19);

if(d == da) {

t.push(ti);

} else {

d = da

var dt = {date: da, time: ti};
newData.push(dt);

}


});

我很难弄清楚这个问题,希望你能帮助我。

谢谢。

最佳答案

尝试使用Array.prototype.reduce功能:

const array = ["2020-01-31 18:31:01", "2020-02-03 14:04:30", "2020-02-04 05:58:48", "2020-02-04 14:11:16"];

const newData = array.reduce((acc, cur) => {
const [date, time] = cur.split(' ');
const dateObj = acc.find(e => e.date === date);
if (dateObj) {
dateObj.time.push(time);
} else {
acc.push({ date, time: [time] });
}
return acc;
}, []);

console.log(newData);

关于javascript - 将数组数据转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60087107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com