What causes the _.sum() function in lodash to not work with objects in Vuejs?

I've encountered an issue where using Vuejs and Lodash in conjunction with a computed property that calculates the sum of a property in a collection results in unexpected behavior. Instead of summing the values, it seems to concatenate the string [object Object].

To illustrate this problem, I have created 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 from the above code snippet is as follows:

Method 1 gives: [object Object][object Object]
Method 2 gives: [object Object][object Object]
Method 3 gives: 15

This issue raises the question of whether there is a solution to resolve the _.sum() problem or if it requires a deeper understanding of why it behaves in this manner.

Answer №1

Consider using sumBy in place of sum:

Instead of using _.sum, you can utilize sumBy which allows you to specify an iteratee function that will be applied to each element in the array before summing up the values.

Answer №2

Consider using the following approach:

computeTotalTime() { return _.sum(this.activities.map(activity => activity.duration)) },

Answer №3

Are you dead set on using _.sum and then mapping? Another approach is to simplify it with:

calculateTotal() { return _.sumBy(this.tasks, 'duration') }

Alternatively, with ES6 syntax, you could shorten it further to:

calculateTotal = () => _.sumBy(this.tasks, 'duration')

This function exemplifies the primary use of _.sumBy.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating interactive carousel slides effortlessly with the power of Angular and the ngu-carousel module

I'm currently tackling the task of developing a carousel with the ngu-carousel Angular module, available at this link. However, I'm facing some challenges in configuring it to dynamically generate slides from an array of objects. From what I&apos ...

Transferring data between AngularJS and non-AngularJS environments

Within my AngularJS application, the $scope.mydata variable holds some important data within a controller. I am currently working on a regular JSP page without any AngularJS functionality, but I need to access the data stored in the scope variable (mydat ...

Setting a specific index in an array of objects in React: A comprehensive guide

I currently have a useState() object structured as follows: const [financeSummary, setFinanceSummary] = useState({ discountRate: 10, financeRate: 10, reinvestRate: 10, inflationRate: 3, singleInvestment: new Array( ...

Issue with Sequelize Associate function not functioning correctly

I've been attempting to connect two tables in Sequelize, but I keep encountering the SequelizeEagerLoadingError indicating that one table is not associated with the other, despite trying all the suggested solutions on this platform. The tables in que ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

React encountered an abrupt end of JSON input unexpectedly

As I embark on my coding journey, I am delving into the world of React. However, as I try to create a new app, I encounter an error message stating "unexpected end of JSON input." While installing packages and waiting patiently, the console throws an err ...

I would like to split a string of characters using spaces XY XYZ XYZ

As a young developer, I am facing a challenge and seeking a solution. The user enters a number in a format like XX XXX XXXX, but I need it to be separated differently. Currently, the numbers are being grouped as XXX XXX XXX, which is not the desired outp ...

Is there a way to use JQuery to make one button trigger distinct actions in two different divs?

For instance: Press a button - one div flies off the screen while another div flies in. Press the button again - Same div flies out, other div returns. I'm completely new to Javascript/JQuery so any assistance would be highly appreciated! Thank you ...

Is there a way to split a <v-carousel-item> within a <v-carousel> component into two columns using Vuetify?

I am looking to incorporate this carousel design into vuetify3. How should I go about it? https://i.stack.imgur.com/XQXOC.jpg ...

Executing AJAX requests to trigger a function in a separate MVC controller using Jquery

Below is the structure of my folders. Both of these folders are located within the Area folder. https://i.sstatic.net/KLGzl.png I'm currently attempting to invoke a function from the EmailController inside ITRequests/Scripts/Edit.js, but it's u ...

Tips for optimizing mobile performance by loading .obj models into objects on three.js

How can I properly load .obj models with objLoader and MTLLoader for my three.js mini game? I am facing an issue where the game loads fine on computers but fails to load on mobile browsers. Specifically, when accessed on a phone browser, the game attempts ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

What could be causing my CSS/Layout to alter once AJAX/JavaScript has been executed?

When the user clicks, an AJAX call is made to retrieve data from a third-party API. The frontend/layout renders correctly before this action; however, after the data is fetched and displayed in the frontend, the layout changes. Upon debugging multiple tim ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

Steps to activate an event when Windows is loaded

Every time windows load, I want to run $('select[name="order_id"]').change(), but it's not working as expected. After debugging in the browser console, I can see that the script $('select[name="order_id"]').cha ...

Struggling with dynamic values and regex while utilizing HTML template strings. Need help overcoming regex challenge

Feeling stuck and seeking advice on improving regex usage. For a one-time substitution, the code below works for replacing a single element like -link-. var testHtmlStr = '<tr>' + '<td class="eve"><div class= ...

Reverse the action and postpone the Ajax call for a specified time or until the next action occurs

How can I implement a setup and undo feature for my ajax calls that allows users to delay the call for a set amount of time and abort it if needed? I also want to be able to stop the delay and proceed with the most recent ajax call if another action is tri ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

The Material-ui Drawer does not function properly when used with an external CSS file

For my project, I'm working on a Sidebar design that is inspired by the Mini Variant drawer demo available at this link. However, the project requirements mandate that all CSS styling should be done in a separate CSS file rather than directly within t ...