I have a computed property in VueJS like this:
computed: {
groupedTemplates() {
const ret = this.templates.reduce((acc, value) => {
value.group = value.group || "Ungrouped";
if (!acc[value.group]) {
acc[value.group] = [];
}
acc[value.group].push(value);
return acc;
}, []);
console.log(ret); // <---- This works!!
return ret;
},
...mapState(["currentPatient", "currentSite", "phrases", "templates"]),
},
When I view the console, I can see the correct response which is
app.js:4061 [Ungrouped: Array(6), Note: Array(2), Order Set: Array(3)]
However, when I use groupedTemplates
in code, it evaluates to []
when I change the return line to
return 34;
It returns 34 as expected. What gives?
Because your reduce
does not add items into the array but creating new properties on Array
object - you can't use a string as an index into an array...
What you probably want is to return Object
from your groupedTemplates
computed...