Is there a clever method (perhaps using a map function) to restructure my data object from this:
[
{id: 1, from: "1/1/2021", to: "1/2/2022"},
{id: 2, from: "1/3/2021", to: "1/4/2022"},
{id: 1, from: "1/5/2021", to: "1/6/2022"},
{id: 2, from: "1/6/2021", to: "1/7/2022"}
]
to the following format:
{
1: [{from: "1/1/2021", to: "1/2/2022"}, {from: "1/5/2021", to: "1/6/2022"}],
2: [{from: "1/3/2021", to: "1/4/2022"}, {from: "1/6/2021", to: "1/7/2022"}]
}
Check out the code snippet below for reference:
const res = [
{id: 1, from: "1/1/2021", to: "1/2/2022"},
{id: 2, from: "1/3/2021", to: "1/4/2022"},
{id: 1, from: "1/5/2021", to: "1/6/2022"},
{id: 2, from: "1/6/2021", to: "1/7/2022"}
]
let dict = {};
for(var i=0; i < res.length; i++) {
dict[res[i].id] = dict[res[i].id] || [];
dict[res[i].id].push({from:res[i].from, to:res[i].to});
}
console.log(dict);