I’m receiving data and scratching my head to find a cleaner way to modify the data in a singular one level array of objects:
data:
{
dayMon: [
{
id: 1,
name: 'whatever'
}
],
dayTues: [],
dayWed: [],
nextWeek: [
{
dayTues: [{
id: 3,
name: 'whatever'
}],
dayMon: [],
dayThurs: []
}
]
}
and my goal is:
[
{
id: 1,
name: 'whatever'
},
{
id: 3,
name: 'whatever'
}
]
so I created a function:
export function buildDays(data: {[s: string]: unknown} | ArrayLike<unknown>) {
const flatDays = Object?.values(data)?.flat() || []
if (!flatDays || flatDays?.length === 0) return null
const nextWeek: unknown[][] = []
if (data.hasOwnProperty('nextWeek')) {
data?.nextWeek.map((day: any) => nextWeek.push(Object?.values(day)?.flat()))
}
const cleaned = [...flatDays, ...nextWeek?.flat()].filter(Boolean)
return cleaned
}
but my issue falls under nextWeek
an at current implementation ...reuseBlock?.flat()
throws a TypeScript warning of:
Unsafe usage of optional chaining. If it short-circuits with ‘undefined’ the evaluation will throw TypeError.
Reading
- best way to convert object with arrays to array with objects and viceversa
- convert an array of objects to one object of objects
- Merge/flatten an array of arrays
- How to convert object of array of object to array of object in Javascript
- How to convert Arrays of objects of objects into one dimensional array?
In Vanilla JavaScript is there a better way to build the data into one array of objects?