This might seem a bit weird but I have a need to merge objects in an existing dataset into a new dataset grouped by a specific key value. Here's the dataset:
const object = [
{
id: 1,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 1'
}
},
{
id: 2,
scheduledAt: '2022-09-10',
organization: {
name: 'Organization 2'
}
},
{
id: 3,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 3'
}
}
]
Here is what I am after as the return dataset:
const objectMerged = {
'2022-09-20': [
{
id: 1,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 1'
}
},
{
id: 3,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 3'
}
}
],
'2022-09-10': [
{
id: 2,
scheduledAt: '2022-09-10',
organization: {
name: 'Organization 2'
}
}
]
}
I have tried many different ways but nothing seems to work correctly. Here's the latest code, which does not work:
const merged = []
object.forEach((item) => {
if (!merged.length) {
// if the return dataset is empty, add this item immediately
merged.push({ [item.scheduledAt]: [item] }
} else {
// check if item already exists with the same scheduledAt as current object and if so, push it into that array as object
// if does not exist, create new array entry with the new scheduledAt name
const find = Object.keys(merged).map((k) => {
console.log(`key ${k}`)
console.log(merged[k])
return Object.keys(merged[k]).map((key) => {
console.log(`key2: ${key}`)
return key === item.scheduledAt
})
})
console.log(find)
}
})
console.log(merged)
Any help is greatly appreciated. Thank you!
CodePudding user response:
By using a reduce you can generate what you want. Please have a look:
const object = [
{
id: 1,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 1'
}
},
{
id: 2,
scheduledAt: '2022-09-10',
organization: {
name: 'Organization 2'
}
},
{
id: 3,
scheduledAt: '2022-09-20',
organization: {
name: 'Organization 3'
}
},
];
const objectMerged = object
.sort((objectA, objectB) =>
objectA.scheduledAt.localeCompare(objectB.scheduledAt)
)
.reduce((acc, cur) => ({
...acc,
[cur.scheduledAt]: [
...(acc[cur.scheduledAt] || []),
cur,
],
}), {});
console.log(objectMerged);