I am trying to convert array of objects to object of array using javascript.
Here is the code
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 = {};
I want to use programs object to make an object out of it like this below.
{
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"
}]
}
}
I try to solve it using map in array method.
data.map(item => {
programs[item.yearMonthKey] : {
programs[item.dayKey] : [{
}]
}
})
but it is bit challenging to sort objects as a value of same dayKey key inside of an array and put those inside of same yearMonthKey.
mapwhen the desired result is a key-value object