I'm having trouble figuring out how to restructure the array below.
I attempted to utilize the reduce function in JavaScript but unfortunately, I couldn't make it work.
So far, this is the function I have come up with:
var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
a.productVariations.forEach(element => {
if (comb.indexOf(element.variationName) === -1) {
comb.push(element.variationName)
let group = element.variationOptions.reduce((r, a) => {
r['variationName'] = element.variationName
r['variationOptions'] = [...(r[a.name] || []), a]
return r
}, {})
group['linked'] = []
setEle.push(group)
}
})
})
How can I reorganize the array as shown below and successfully use my reduce function?
var input = [
{
companyName: 'ABC',
productVariations: [
{
variationName: 'Colour',
variationOptions: [
{
name: 'Blue'
},
{
name: 'Red'
}
]
},
{
variationName: 'Pattern',
variationOptions: [
{
name: 'Bold'
},
{
name: 'Spotted'
}
]
}
]
},
{
companyName: 'BBC',
productVariations: [
{
variationName: 'Colour',
variationOptions: [
{
name: 'Blue'
},
{
name: 'Red'
},
{
name: 'Purple '
}
]
}
]
}
]
This is the desired output format:
var output = [
{
variationName: 'Colour',
variationOptions: [
{
name: 'Blue'
},
{
name: 'Purple'
},
{
name: 'Red'
},
],
linked: [
{
companyName: 'BBC'
},
{
companyName: 'ABC'
}
]
},
{
variationName: 'Pattern',
variationOptions: [
{
name: 'Bold'
},
{
name: 'Spotted'
},
],
linked: [
{
companyName: 'ABC',
}
]
}
]
In the output array, the variationOptions
are grouped by variationName
and the relevant companyName is added to the linked
child array.