Generating specific output based on the provided input parameter in JavaScript

I have encountered a problem where I am able to get the output, but I am struggling to figure out how to change certain elements. Specifically, I have the total salary but I am unsure how to modify the keys and achieve the desired format.

The desired output format is as follows:

{
    "433": {
        employee_name: 'Rishi',
        total_salary: 5200
  },
    "434": {
        employee_name: 'pathak',
        total_salary: 5600 
  },
    "435": {
        employee_name: 'partap',
        total_salary: 5700
      }
  } 
function takeInput(output){
            let total = [];
            let totalSalary = [];
            for(let i=0; i< output.length; i++){
                if(typeof(output[i].employee_data.salary[0]) == "object"){
                    total[i] = output[i].employee_data.salary[0];  
                    totalSalary[i] = addSalary(total[i]);
                    output[i].employee_data.salary[0]  = addSalary(total[i]);
                    console.log(output[i]);  
                }
            }
        }
        
        function addSalary(income){
            let total = 0;
            let values = Object.values(income)
            for(let i=0; i< values.length; i++){
              total = total + values[i];
            }
            return total;
        }
        
        
        
        let output = [
            {
              employee_data: {
                  employee_name: 'Rishi',
                  id: "433",
                  salary: [{'march': 1200, 'april': 2000, 'may': 2000}]
              }
            },
            {
                employee_data: {
                  employee_name: 'pathak',
                  id: "434",
                    salary: [{'march': 1100, 'april': 2200, 'may': 2300}]
                }
            },
            {
                employee_data: {
                  employee_name: 'partap',
                  id: "435",
                    salary: [{'march': 1200, 'april': 2200, 'may': 2300}]
                }
            }
        ]

Answer №1

    let data = [
    {
      employee_info: {
          name: 'Elena',
          id: "436",
          earnings: [{'january': 1500, 'february': 1800, 'march': 1900}]
      }
    },
    {
        employee_info: {
          name: 'Michael',
          id: "437",
            earnings: [{'january': 1600, 'february': 2000, 'march': 2100}]
        }
    },
    {
        employee_info: {
          name: 'Sophia',
          id: "438",
            earnings: [{'january': 1700, 'february': 2200, 'march': 2300}]
        }
    }
]

function calculateTotal(income){
    let totalIncome = 0;
    let values = Object.values(income)
    for(let i=0; i< values.length; i++){
      totalIncome = totalIncome + values[i];
    }
    return totalIncome;
}

const updateData = (data) => {
    const newData = {}
    data.forEach(d => {
        newData[d.employee_info.id] = {
            name: d.employee_info.name,
            earnings: calculateTotal(d.employee_info.earnings[0])
        }
    })
    console.log(newData);
}

updateData(data);

Answer №2

To achieve the desired outcome, you can utilize multiple instances of the reduce() method.

const data = [{
    employee_data: {
      employee_name: 'Rishi',
      id: "433",
      salary: [{
        'march': 1200,
        'april': 2000,
        'may': 2000
      }]
    }
  },
  {
    employee_data: {
      employee_name: 'pathak',
      id: "434",
      salary: [{
        'march': 1100,
        'april': 2200,
        'may': 2300
      }]
    }
  },
  {
    employee_data: {
      employee_name: 'partap',
      id: "435",
      salary: [{
        'march': 1200,
        'april': 2200,
        'may': 2300
      }]
    }
  }
];

const result = data.reduce((obj, user) => {
  obj[user.employee_data.id] = {
    "employee_name": user.employee_data.employee_name,
    "total_salary": user.employee_data.salary.reduce((total, current) => {
      return total + Object.values(current).reduce((num1, num2) => num1 + num2, 0);
    }, 0),
  };
  return obj;
}, {});

console.log(result);

Answer №3

let data = [{employee_data: {employee_name: 'Rishi',id: "433",salary: [{'march': 1200,'april': 2000,'may': 2000}]}},{employee_data: {employee_name: 'pathak',id: "434",salary: [{'march': 1100,'april': 2200,'may': 2300}]}},{employee_data: {employee_name: 'partap',id: "435",salary: [{'march': 1200,'april': 2200,'may': 2300}]}}];

// combining multiple entries into a single object
let mergedData = data.reduce((obj, entry) => {
  
  // extract employee details from each entry
  let { employee_name, id, salary } = entry.employee_data;
  
  // create new entry based on unique id
  obj[id] = { employee_name, salary };
  
  // return the updated object
  return obj;
  
}, {} /* starting with an empty object */ );

console.log(mergedData);
.as-console-wrapper {min-height:100%} /* styling for preview */

Answer №4

To calculate the totals, utilize multiple reduce() functions.

 // loop through the data array
let result = data.reduce((accumulator, current) => ({ ...accumulator, 
 // merge with the accumulator by creating a new object with employee id as the key
  ...{ [current.employee_data.id]: {
        employee_name: current.employee_data.employee_name,
        // total salary is computed by summing all values in the salary object
        total_salary: Object.values(current.employee_data.salary[0]).reduce((sum, value) => sum + value, 0)
      }
    }
  }), {})

let data = 
    {
      employee_data: {
          employee_name: 'Rishi',
          id: "433",
          salary: [{'march': 1200, 'april': 2000, 'may': 2000}]
      }
    },
    {
        employee_data: {
          employee_name: 'pathak',
          id: "434",
            salary: [{'march': 1100, 'april': 2200, 'may': 2300}]
        }
    },
    {
        employee_data: {
          employee_name: 'partap',
          id: "435",
            salary: [{'march': 1200, 'april': 2200, 'may': 2300}]
        }
    }
]

// iterate through the data array
let output = data.reduce((b, a) => (
 // return the accumulator b, adding in...
  { ...b, ...{
  // a new object with the employee id as the key
      [a.employee_data.id]: {
        employee_name: a.employee_data.employee_name,
        // the total salary is summed through another reduce, this time, taking the Object.values() of salary and adding them together
        total_salary: Object.values(a.employee_data.salary[0]).reduce((d, c) => d + c, 0)
      }
    }
  }), {})
  
console.log(output)

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

Implement a check for the existence of a character in a string through the strstr() function in C

This particular issue seems to revolve around the use of the char data type and pointers. void main() { const char* a; char character = 65; a = &character; printf("%c \n", character); // OUTPUTS 'A' AS EXPECTE ...

JavaScript: Extending a class with an invalid or null value is not permitted

Trying my hand at constructing a page object for login testing with WebdriverIO. Encountering the error ERROR: Class extends value #<Page> is not a function or null on line 3 of login.page.js. No clue what mistake I'm making... Is there a wron ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

Can 2D canvas elements make use of CSS shaders?

Can CSS shaders, like "fragment" shaders, be utilized in 2D canvas contexts as well? ...

I am looking to generate a PostgreSQL view that can extract the contents of a JSON column

This query creates a view in PostgreSQL that displays data from JSON columns (labtestgroup and price). CREATE OR REPLACE VIEW public.orders_with_prices AS SELECT o.id, replace(''::text || o.labtestgroup, '"'::text, '' ...

Re-sorting with _.sortBy() eliminates additional 0s from decimal values (transforming 0.10 to 0.1 and beyond)

Here is an array that needs to be sorted: var baseBetAmount = [ { val: 'OtherBaseBet', text: 'Other' }, { val: 0.10, text: '$0.10' }, { val: 0.20, text: '$0.20' }, { val: 0.50, text: ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Is there a way to use fetch() to automatically redirect a user after logging in?

I'm currently working on a node.js application using express, and I am in the process of creating a login form for my users. I want to include a Javascript file that utilizes fetch() to send a POST request to my API for user authentication. However, I ...

Struggling to enable Google Cast functionality on Apache Cordova: Unhandled error - chrome is not recognized

Struggling to integrate Google Cast with Apache Cordova, I'm facing challenges due to outdated guides and plugins. Despite finding a recently updated plugin three months ago, I keep encountering this error: Uncaught ReferenceError: chrome is not defi ...

What is the most efficient way to transform HTML into React components effortlessly?

I have been attempting to automate the process of converting HTML into React components. I followed the link below to automatically convert HTML into React components: https://www.npmjs.com/package/html-to-react-components However, I encountered an issue ...

What is the best way to extract all "conditions" nested under the key "logic" at the 0th index in a JSON object?

I need to manipulate a nested object by removing every "condition" where the key is "logic" and the value is 0 from it. Here is an example of the object structure: Original input: [ { "conditions": [ { "logic": "AND", "paramet ...

Updating a MongoDB array using a different field

I am working with a database that has fields f1, f2, and f3 (which is an array). I would like to perform an update operation like this: db.collection.update ({f1:1},{$push:{f3:{$each:[f2's value],$slice:-2}}}) After searching online, I couldn&apos ...

Implementing an interactive tab feature using jQuery UI

Recently, I was working on a project involving HTML and jQuery. Now, my goal is to create a dynamic tab with specific data when a button is clicked. This is my code for the JQuery-UI tab: $(document).ready(function() { var $tabs = $("#container-1 ...

Tips for personalizing dual data binding in AngularJS

Here is the HTML code: <select data-ng-options="o.id as o.device for o in deviceList" data-ng-model="selectedDeviceID"></select> <input type="text" id="deviceWidth" ng-model="deviceList[selectedDeviceID].width" placeholder="width"/> ...

JavaScript/jQuery: What is the best way to assign an element as the context ('this') of a function?

Is there a way to pass something to a function and have it act as if it's calling the function itself? Consider this function: function ShowId() { alert($(this).attr('id')); } and this block of HTML: <div id='div1'> & ...

Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects. window.addEventListe ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

Uploading files to an S3 bucket with Node.js

Currently, I am utilizing Sailsjs version 0.12.1 along with node.js 4.2.6 My objective is to upload a file from the front-end (built using angular.js) through an API and then proceed to upload this file to an AWS S3 bucket from the backend. When sending ...

Mapping objects in an array with Javascript

This code snippet is intended for a React Native Chat app. The structure of my data should look something like this: const chatData = [ { id: 1, name: 'John Doe', messages: [ {text: 'Hello', sentAt: 'time here' ...

Can CSS be used to create curved dashed lines?

Is it possible to achieve dashed lines similar to the ones highlighted in the images below using only CSS? I have a responsive web page built with Bootstrap, and I need the dashed lines to adjust accordingly when the window width changes. https://i.sstat ...