Changing a JavaScript array by including a numerical value

Here is my original dataset...

[{
        month: 'Jan',
        cat: 'A',
        val: 20
    },{
        month: 'Jan',
        cat: 'B','
        val: 5
    },{
        month: 'Jan',
        cat: 'C',
        val: 10
    },{
        month: 'Feb',
        cat: 'A',
        val: 30
    },{
        month: 'Feb',
        cat: 'B',
        val: 10
    },{
        month: 'Feb',
        cat: 'C',
        val: 20
    }];

I want to convert it to the following structure..

[{
            dim:'val'
        x: 'Jan',
            nval: 20 //same as base object val
        },{
            dim:'val'
            x: 'Jan',
            nval: 25// 20+5 -> above nval value + base object val
        },{
            dim:'val'
            x: 'Jan',
            nval: 35//25+10
        },{
            dim:'val'
            x: 'Feb',
            val: 65//35+30
        },{
            dim:'val'
            x: 'Feb',
            nval: 75
        },{
            dim:'val'
            x: 'Feb',
            nval: 95
        }];

The new array in JavaScript has a fixed property dim with the value 'val'. The property x takes the value from the base object's month. The nval property in each object starts with the base object's val and then gets incremented by the base object's val in the previous object.

If you need further clarification, feel free to ask any questions.

I believe I can create the new JavaScript array using the map function, but I'm not sure about calculating and adding the values for nval based on the values of val.

Any assistance would be greatly appreciated.

Thank you!

Answer №1

Hopefully, this code snippet proves helpful.

var newObj=[];
var temp=0;
var arr =[{
        month: 'January',
        category: 'A',
        value: 20
    },{
        month: 'January',
        category: 'B',
        value: 5
    },{
        month: 'January',
        category: 'C',
        value: 10
    },{
        month: 'February',
        category: 'A',
        value: 30
    },{
        month: 'February',
        category: 'B',
        value: 10
    },{
        month: 'February',
        category: 'C',
        value: 20
    }];

for(var key in arr)
{
  newObj.push({
    'dimension':'value',
    'x':arr[key]['month'],
    'nvalue':temp + arr[key]['value']
  });
  temp=temp + arr[key]['value'];
}

console.log(newObj);

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

Vue.js routing and mixin dilemma

Calling all Vue developers! I am currently working on a vuebnb tutorial and running into an issue with routing and mixins. I have attempted to assign data before entering the router using the beforeRouteEnter guard, but it seems like my template is being r ...

Is there a way to replicate Twitter's "what's happening" box on our website?

Currently, I am trying to extract the cursor position from a content-editable box. However, when a new tag is created, the cursor appears before the tag instead of after it. Additionally, I am having trouble with merging/splitting the tags. Any suggestions ...

Is it possible to incorporate npm modules into a browser and utilize them locally on a personal computer?

This is my first time working with npm modules and node.js, so I find it quite challenging. I have a JavaScript code with multiple data points and I need to find the closest city to each of them. In response to another question on Stack Overflow (Reverse ...

Using ThreeJS/WebGL to Send Functions to Shaders

I have created a custom noise function that accepts a 3D coordinate (x, y, z) and returns a noise value between 0 and 1. I am interested in incorporating this function into my vertex shader to animate vertex positions. Can I access this external function f ...

We encountered a sudden termination of JSON data while parsing near '...w2BfLygJAO9ZBvYIqZTld'

Encountered an error when trying to initialize a new React App. command: $npx create-react-app yourblog Node --version v12.16.2 npx --version 6.14.4 Click here to view the error ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

Updating results in Angular.js based on variable changes

After setting some data in the window, I am facing issues with updating an angular.js table created using the smart table module/plugin. The data is structured like this: window.checker={};window.checker.checked = [{'ip':9,'port':0}] ...

Changing column sorting type dynamically with a button click using jQuery and DataTables

In the column, I have data arranged as "firstValue secondValue". It is essential for this data to remain in a single column and not split into two separate columns. When sorting is applied, it currently sorts based on both firstValue and secondValue. How ...

Unable to run the JSON.parse() function while using the 1.10.2 version of jquery.min.js

Has anyone else encountered a situation where using JSON.parse() to parse the PHP array return only works when applying 1.3.2/jquery.min.js and not 1.10.2/jquery.min.js? If so, what solution did you find? PHP array return $returnArray['vercode' ...

What is the best way to initially expand specific nodes in d3.js?

I am currently experimenting with and making adjustments to this d3.js example in order to create a tree based on a JSON structure. In this tree, the root node is initially expanded while all other nodes are collapsed. My goal is to modify it by providin ...

Consecutive pair of JavaScript date picker functions

My issue involves setting up a java script calendar date picker. Here are my input fields and related java scripts: <input type="text" class="text date" maxlength="12" name="customerServiceAccountForm:fromDateInput" id="customerServiceAccountForm:from ...

Exploring Vue JS: Decoupling variables in separate files and effective ways of accessing them

In my Vue project, I am looking to create a dedicated .js file to store multiple variables that can be easily accessed by other components. I am seeking advice on the most efficient method to achieve this and would greatly appreciate any examples provide ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

Having trouble retrieving the recently updated data from the useReducer hook within a function defined in setTimeout

Within my application, I have encountered an issue while using a dispatch from the useReducer hook. Specifically, when I trigger a click event on a button that contains a setTimeout function of 2 seconds, the updated value is not reflected in the setTimeou ...

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no e ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

What are the best scenarios for implementing jQuery-ui plugin as opposed to Backbone View?

I am feeling uncertain about the concept of "componentization" in web UI development. When I need a component, should I develop my own jQuery-UI plugin or opt for creating a MarionetteComponent if I am using Backbone.Marionette? Both options provide reusa ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...