I have an array of objects and Iām trying to combine them together into a single object, based on their values.
For example, if I have this array:
const arr = [
{mo: true, tu: true, we: {...another object}, th: true, fr: true, sa: {...aDifferentObject}, su: true},
{mo: {...aThirdObject}, tu: true, we: true, th: true, fr: true, sa: true, su: true}
I would then want to return:
console.dir(combineObjects(arr))
// {mo: {...aThirdObject}, tu: true, we: {...another object}, th: true, fr: true, sa: {...aDifferentObject}, su: true},
With that, I also need to decide on what to do when multiples keys of the same name have objects in them.
I've tried various methods like arr.reduce()
and Object.keys(arr[0]).forEach()
but reduce()
returns an array and Object.keys().forEach()
gets really messy really quickly.
Is there an easier way to do this? I feel like I must be overthinking it.
[EDIT: The actual input and expected output were requested in the comments]
// Input
[{fr:{
beginWork: ['08', '00'],
end: ['23', '59'],
endWork: ['16', '15'],
start: ['00', '00'],
},
mo: true,
sa: true,
su: {
beginWork: ['08', '00']
end: ['23', '59']
endWork: ['16', '15']
start: ['00', '00']
},
th: true,
tu: {
beginWork: ['08', '00']
end: ['23', '59']
endWork: ['16', '15']
start: ['00', '00']
},
we: true,
},
{
fr: {
end: ['13', '00']
start: ['00', '00']
},
mo: {
end: ['13', '00']
start: ['00', '00']
},
sa: {
end: ['13', '00']
start: ['00', '00']
},
su: {
end: ['13', '00']
start: ['00', '00']
},
th: {
end: ['13', '00']
start: ['00', '00']
},
tu: {
end: ['13', '00']
start: ['00', '00']
},
we: true
}]
// Expected output
{
fr:{
beginWork: ['08', '00'],
end: ['23', '59'],
endWork: ['16', '15'],
start: ['00', '00'],
},
mo: {
end: ['13', '00']
start: ['00', '00']
},
sa: {
end: ['13', '00']
start: ['00', '00']
},
su: {
beginWork: ['08', '00']
end: ['23', '59']
endWork: ['16', '15']
start: ['00', '00']
},
th: {
end: ['13', '00']
start: ['00', '00']
},
tu: {
beginWork: ['08', '00']
end: ['23', '59']
endWork: ['16', '15']
start: ['00', '00']
},
we: true,
},
Please and thank you in advance :)
I hope you all have a great day!