I'm using Vuejs and Lodash and I have a computed property that simply sums a property of a collection. I've previously used _.sum()
for this but when I use that with a vuejs vm it seems to just concatenate the string [object Object]
!
I've made a jsfiddle with the following code:
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", time: 5 },
{ text: "Learn Vue", time: 10 },
]
},
computed: {
additup() { return _.sum(this.todos, todo => todo.time ) },
additup2() { return _.sum(this.todos, function (todo) {
return parseInt(todo.time);
})} },
additup3() {
var t = 0;
_.each(this.todos, function(todo) { t+=todo.time; });
return t;
}
}
})
The output is:
Method 1 gives: [object Object][object Object]
Method 2 gives: [object Object][object Object]
Method 3 gives: 15
Is there a way to fix _.sum()
? Or a way to fix my understanding of why it's not working ;-)
Use sumBy
instead of sum
:
This method is like
_.sum
except that it accepts iteratee which is invoked for each element in array to generate the value to be summed. The iteratee is invoked with one argument: (value).