Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with:

[{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }]

I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property.

For example:

[{ Year:2000, Jan:1, Feb:, Total: 1 }, {Year:2001, Jan:2, Feb:4, Total: -0.66 }]

Can someone provide guidance on how to achieve this using JavaScript?

UPDATE: The array now includes decimal values

Answer №1

When interpreting Feb as having a value of 0 when empty, this code will successfully execute.

var data = [{ Year:2000, Jan:1, Feb:0 }, {Year:2001, Jan:2, Feb:4 }];

data.forEach(item => {
    item.Total = item.Jan + item.Feb;
});


console.log(data); /* [
  { Year: 2000, Jan: 1, Feb: 0, Total: 1 },
  { Year: 2001, Jan: 2, Feb: 4, Total: 6 }
]*/


Answer №2

Consider this scenario:

const data = [{ Year:2000, Jan:1, Feb: 2}, {Year:2001, Jan:2, Feb:4 }];

An easy solution is to loop through the months.

data.forEach(item => item.Total = item.Jan + item.Feb)

If needed, you can include more months in the calculation

data.forEach(item => item.Total = item.Jan + item.Feb + item.Mar + item.Apr)

Answer №3

Assume that the variable data holds an array of objects.

const data = [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:2, Feb:4 }]

To modify the existing array, you can utilize Array.forEach.

data.forEach((item) => {
    const total = (item.Jan || 0) + (item.Feb || 0);
    item.Total = total;
});

In this scenario, (item.Jan || 0) ensures a default value of 0 for undefined Jan.

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

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

What types of modifications do ViewChildren and ContentChildren QueryLists keep an eye out for?

Imagine you come across the following lines of code: https://i.stack.imgur.com/7IFx1.png And then, in a different section, you stumble upon this code block: https://i.stack.imgur.com/qac0F.png Under what circumstances would () => {} be executed? Wha ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

Using async await in a React component causes a syntax error

Struggling with setting up a basic react app using hapi.js on the server-side, I am diving into the world of webpack and babel as a newcomer. Here's a glimpse at my React component App.jsx: import React from 'react'; export default class A ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

Learning how to toggle default snippet keywords on and off based on specific scenarios within the Angular Ace Editor

Within the Ace editor, I have incorporated custom snippets alongside the default ones. However, there are certain scenarios where I would like to exclusively display the custom snippets and hide the default ones. Is there a way to disable or conceal the ...

Building a personalized command-line interface (CLI) tool using Typescript

I recently created a Typescript program that converts various .json file formats. However, I realized that I have hardcoded the file path for reading. const file = readFileSync('./name_of_file_path.json', 'utf-8'); // fixed file path. f ...

Extract particular elements from an array and transform them into a new array

Presented below is an array: [{ "title": "Apple iPhone 7 Plus 32 GB", "category": "phone", "brand": "apple", "condition": "Used", "price": 800, "id": 0, "description": "Apple" }, { "title": "Apple Ipad Air 32 GB", "category": "tablet", "brand ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

The jQuery($) function cannot be accessed within the module file

I have been utilizing webpack to consolidate my code. The following excerpt is from my main.js file where I am including jQuery. main.js var $ = global.jQuery = require('jquery'); $('someSelector').on('rest of the code.& ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

What is the reason behind In-memory-web-api not generating an ID?

While I have successfully implemented the GET, PUT, and DELETE methods using InMemoryDbService to simulate an API, I am facing issues with the CREATE method. It seems like the ID is not being generated in the route to display my add form. The error message ...

JavaScript ES6 array method for generating an object from an array

I wish to transform the following array: [ { event: "LIB", block_calendar: "YES", obs: "Lorem Ipsum", status: "Block", }, { event: "LIB" block_calendar: "YES" o ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

MUI Select component not displaying top border

Can anyone help me understand why the select field is behaving this way? I'm new to the project and suspect that someone may have made changes to it. <mui.FormControl style={{ width: '598px' }}> <mui.InputLabe ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Is it possible to determine the location of the "phantom image" while moving an object?

Is there a method to retrieve the location of the ghost image when an element is dragged? This is how the scenario is set up: <div id="test" v-on:dragstart="dragStart" v-on:drag="dragging" draggable="true" v-on:drop="drop" v-on:dragover="allowDrop"> ...