Does anyone know how to turn this:
Map {
0: { hangWithFriends: 100 },
1: { Chill: 30, Book: 80 },
2: { Yoga: 40 },
3: { Birthday: 200 },
4: { Gas: 70 },
5: { Rent: 900, testingsub: 200 },
6: { testSub: 500 }
}
into this:
[
{date: 0, hangWithFriends: 100},
{date:1, Chill: 30, Book:80},
{date: 2, Yoga:40},
{date: 3, Birthday:200},
{date:4, Gas:70},
{date:5, Rent:900, testingsub:200},
{date: 6, testSub: 500}
]
I tried this:
reducedMonths.forEach((date, obj) => {
newData.push({ date, ...obj });
});
But got this and I know it’s because I’m spreading but I don’t know how else to add a dynamic amount of props:
Array(7) [
{ date: { hangWithFriends: 100 } },
{ date: { Chill: 30, Book: 80 } },
{ date: { Yoga: 40 } }, { date: { Birthday: 200 } },
{ date: { Gas: 70 } },
{ date: { Rent: 900, testingsub: 200 } },
{ date: { testSub: 500 } }
]
>Solution :
You could spread the map entries iterator into an array, and map the key to a parsed date integer and spread the values.
Make sure you sort the dates at the end, because sorting order is not guarenteed.
const dataMap = new Map(Object.entries({
'0': { 'hangWithFriends': 100 },
'1': { 'Chill': 30, 'Book': 80 },
'2': { 'Yoga': 40 },
'3': { 'Birthday': 200 },
'4': { 'Gas': 70 },
'5': { 'Rent': 900, 'testingsub': 200 },
'6': { 'testSub': 500 }
}));
const dataArr = [...dataMap.entries()]
.map(([key, value]) => ({ date: +key, ...value }))
.sort((a, b) => a.date - b.date);
console.log(dataArr);
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to optimize this, you can use an iterator to skip converting the entries into an array, prior to calling Array.prototype.map.
const dataMap = new Map(Object.entries({
'0': { 'hangWithFriends': 100 },
'1': { 'Chill': 30, 'Book': 80 },
'2': { 'Yoga': 40 },
'3': { 'Birthday': 200 },
'4': { 'Gas': 70 },
'5': { 'Rent': 900, 'testingsub': 200 },
'6': { 'testSub': 500 }
}));
const dataArr = [];
for (let [key, value] of dataMap) {
dataArr.push({ date: +key, ...value });
}
dataArr.sort((a, b) => a.date - b.date); // Make sure you sort
console.log(dataArr);
.as-console-wrapper { top: 0; max-height: 100% !important; }