gpt4 book ai didi

javascript - 如何在javascript中将对象数组转换为数组对象?

转载 作者:行者123 更新时间:2023-11-30 08:17:42 25 4
gpt4 key购买 nike

我正在尝试使用 javascript 将对象数组转换为数组对象。

这是代码

const data = [{
yearMonthKey: "201907",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
},
{
yearMonthKey: "201907",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
},
{
yearMonthKey: "201907",
dayKey: "16",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma12313"
},
{
yearMonthKey: "201908",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
}]

let programs = {};

我想使用 programs 对象来制作一个对象,如下所示。

{
201907: {
15: [{
yearMonthKey: "201907",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
},
{
yearMonthKey: "201907",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma123132"
}],
16: [{
yearMonthKey: "201907",
dayKey: "16",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
}]
},
201908: {
15: [{
yearMonthKey: "201908",
dayKey: "15",
startDate: "2019-07-15 00:00:00+0900",
title: "testProgrma"
}]
}
}

我尝试在数组方法中使用 map 来解决它。

data.map(item => {
programs[item.yearMonthKey] : {
programs[item.dayKey] : [{

}]
}
})

但是将对象排序为数组中相同 dayKey 键的值并将它们放在相同的 yearMonthKey 中有点挑战。

最佳答案

你可以 reduce阵列。将每个 yearMonthKey 添加到累加器。基于 yearMonthKeyacc[yearMonthKey] 对象添加一个嵌套的 dayKey 键并将其默认为数组。

const data=[{yearMonthKey:"201907",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"},{yearMonthKey:"201907",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"},{yearMonthKey:"201907",dayKey:"16",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma12313"},{yearMonthKey:"201908",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"}];

const output = data.reduce((acc, o) => {
if (!acc[o.yearMonthKey])
acc[o.yearMonthKey] = {};

if (!acc[o.yearMonthKey][o.dayKey])
acc[o.yearMonthKey][o.dayKey] = [];

acc[o.yearMonthKey][o.dayKey].push(o);

return acc;
}, {})

console.log(output)

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

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