2👍
✅
This snippet should solve the hardest part of your problem (using ES6 syntax):
const data = [{
"date": "2016-05-01T00:00:00",
"productInformation": [{
"productName": "Apple",
"totalWeight": 200
}]
}, {
"date": "2016-09-01T00:00:00",
"productInformation": [{
"productName": "Apple",
"totalWeight": 632
}, {
"productName": "Mango",
"totalWeight": 856
}, {
"productName": "Spinach",
"totalWeight": 545
}, {
"productName": "Grapes",
"totalWeight": 338
}]
}, {
"date": "2017-01-01T00:00:00",
"productInformation": [{
"productName": "Mango",
"totalWeight": 500
}]
}]
const uniq = a => [...new Set(a)]
const flatten = a => [].concat.apply([], a)
// step 1: find the distinct dates: ["2016-05-01T00:00:00", ... ]
const dates = data.map(e => e.date)
// step 2: find the distinct labels: [Apple, Mango, ... ]
const labels = uniq(
flatten(data.map(e => e.productInformation))
.map(e => e.productName))
// step 3: map the labels to entries containing their data by searching the original data array
const result = labels.map(label => {
return {
label,
data: dates.map(date => {
const hit = data.find(e => e.date === date)
.productInformation
.find(p => p.productName === label)
return hit ? hit.totalWeight : 0
})
}
})
console.log(result)
Source:stackexchange.com