Working with an object array, I am needing to update the count for any object with a type of Select (Multiple Answer).
Each object with a type of Select (Multiple Answer) contains a data object array with a comma separated value like "Overpriced,Unique,High quality". These values should be separated into their own object and be included in a new count and total (sum of all count values) for that particular data object array.
const arr = [
{
data: [
{count: 7, total: 7, value: "N/A"},
],
name: "item 1",
type: "Yes/No",
}, {
data: [
{count: 5, total: 7, value: "N/A"},
{count: 2, total: 7, value: "Yellow"},
],
name: "item 2",
type: "Select (Single Answer)",
}, {
data: [
{count: 5, total: 7, value: "N/A"},
{count: 1, total: 7, value: "Overpriced,Unique,High quality"},
{count: 1, total: 7, value: "Reliable,High quality"},
],
name: "item 3",
type: "Select (Multiple Answer)",
},
];
Expected Result
const result = [
{
data: [
{count: 7, total: 7, value: "N/A"},
],
name: "item 1",
type: "Yes/No",
}, {
data: [
{count: 5, total: 7, value: "N/A"},
{count: 2, total: 7, value: "Yellow"},
],
name: "item 2",
type: "Select (Single Answer)",
}, {
data: [
{count: 5, total: 10, value: "N/A"},
{count: 2, total: 10, value: "High quality"},
{count: 1, total: 10, value: "Overpriced"},
{count: 1, total: 10, value: "Unique"},
{count: 1, total: 10, value: "Reliable"},
],
name: "item 3",
type: "Select (Multiple Answer)",
},
];
I have started down the path of using a reduce function, but it produces an object far from the desired result:
Current Code
arr.reduce((a, c) => {
a[c.data.value] = a[c.data.value] || { total: 0 };
a[c.data.value].total += 1;
return a;
}, {})
Undesired Outcome
{ undefined: { total: 4 } }
totalmeans?totalwould equal the sum of allcountvalues inside eachdataarray.totalif it can be computed. Or rather you can store it but it should be based on the sum of the counts and not have duplicates. It's can easily be wrong or annoying to mess with based on how it's handled at the moment.High qualityhas a count of2as it occurs twice within that particulardataarray. Thetotalserves as basis for knowing the total of thecountvalues within that particulardataarray after the re-count of the comma separated values.