Develop a map in JavaScript that uses a parent key to filter data from an object and then stores it in the map

    con_data = {
      "0": {
        "Actual1920": 2379403,
        "Budget1920": 10121051.161450788,
        "CostOwner": "Dr. Ratnavat",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Salary",
        "LedgereType": "Salary-Teaching",
        "RemainingAmount": 7741648.161450788,
        "leadgerLevel": "EBITDA"
      },
      "1": {
        "Actual1920": 0,
        "Budget1920": 0,
        "CostOwner": "Dr. Ratnavat",
        "LedgerBudget": "Salary",
        "LedgerType": "Salary-Teaching",
        "RemainingAmount": 0
      },
      "2": {
        "Actual1920": 0,
        "Budget1920": 0,
        "CostOwner": "Dr. Ratnavat",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Salary",
        "LedgereType": "Salary-Contract & Professional",
        "RemainingAmount": 0,
        "leadgerLevel": "EBITDA"
      },
      "3": {
        "Actual1920": 0,
        "Budget1920": 540098.7555555556,
        "CostOwner": "Vineeta S",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Admission",
        "LedgereType": "Admission-Referral",
        "RemainingAmount": 540098.7555555556,
        "leadgerLevel": "EBITDA"
      },
      "4": {
        "Actual1920": 0,
        "Budget1920": 40835.600000000006,
        "CostOwner": "Vineeta S",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Admission",
        "LedgereType": "Admission-Others",
        "RemainingAmount": 40835.600000000006,
        "leadgerLevel": "EBITDA"
      },
      "5": {
        "Actual1920": 0,
        "Budget1920": 1690058.304,
        "CostOwner": "Nitin P",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Advertisement",
        "LedgereType": "Advertisement- Print & Others",
        "RemainingAmount": 1690058.304,
        "leadgerLevel": "EBITDA"
      },

// Other objects excluded for brevity

    


 this.new_data = Object.keys(this.con_data).reduce( (acc,currentKey)=>{
  const item = this.con_data[currentKey]
  const ledgetBudgetType = item.LedgerBudget
   if( !acc[ledgetBudgetType] ){
     acc[ledgetBudgetType] = {}
   }
   const size = Object.keys(acc[ledgetBudgetType]).length
   acc[size] = item
   
   return acc
}, {})
console.log("New Data :",this.new_data);
I have an array of objects and I am trying to filter the data into a new object based on a common key in the objects.

The parent key will be the LedgerBudget key, and I want the data formatted as shown below:

new_data = {
'Salary' : {

       "0" :  {
        "Actual1920": 2379403,
        "Budget1920": 10121051.161450788,
        "CostOwner": "Dr. Ratnavat",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Salary",
        "LedgereType": "Salary-Teaching",
        "RemainingAmount": 7741648.161450788,
        "leadgerLevel": "EBITDA"
       },
       "1": {
        "Actual1920": 0,
        "Budget1920": 0,
        "CostOwner": "Dr. Ratnavat",
        "LedgerBudget": "Salary",
        "LedgerType": "Salary-Teaching",
        "RemainingAmount": 0
        },
        "2": {
            "Actual1920": 0,
            "Budget1920": 0,
            "CostOwner": "Dr. Ratnavat",
            "LTRevExp": "Expense-EB",
            "LedgerBudget": "Salary",
            "LedgereType": "Salary-Contract & Professional",
            "RemainingAmount": 0,
            "leadgerLevel": "EBITDA"
            },
},
"Admission" : {
    "0": {
        "Actual1920": 0,
        "Budget1920": 540098.7555555556,
        "CostOwner": "Vineeta S",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Admission",
        "LedgereType": "Admission-Referral",
        "RemainingAmount": 540098.7555555556,
        "leadgerLevel": "EBITDA"
        },
    "1": {
        "Actual1920": 0,
        "Budget1920": 40835.600000000006,
        "CostOwner": "Vineeta S",
        "LTRevExp": "Expense-EB",
        "LedgerBudget": "Admission",
        "LedgereType": "Admission-Others",
        "RemainingAmount": 40835.600000000006,
        "leadgerLevel": "EBITDA"
        },
}

}

Answer №1

Here is a possible solution that may be helpful

const newData = Object.keys(data).reduce( (accumulator,currentKey)=>{

   const currentItem = data[currentKey]
   const budgetType = currentItem.BudgetType

   if( !accumulator[budgetType] ){
     accumulator[budgetType] = {}
   }

   const size = Object.keys(accumulator[budgetType]).length

   accumulator[budgetType][size] = currentItem

   return accumulator

}, {})

Remember, the variable data in this example is an object and not an array. Therefore, you should use Object.keys or Object.entries to iterate over it.

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

Dim the background for all elements except for one

Seeking a way to create a dimmed-background effect by adjusting the opacity of all elements on the page except for one specific element. I've experimented with using the :not() selector as well as jQuery selectors to exclude certain elements, but have ...

Unable to convert a dictionary to JSON using a specialized encoder

I tried to create a specialized JSON encoder and encountered an issue that I cannot comprehend. Following the guidelines outlined in the official Python documentation, I attempted to encode a dictionary using the standard JSON encoder. However, when I con ...

Pass along complex JSON data structure from the view to the model

Is there a way to efficiently send Nested JSON data from the view to the model? Most solutions I've found don't account for variable keys within the object. Here's an example of the JSON object: "Login": { "userId": "harshal.bulsara", ...

Displaying Grunt Command-Line Output in Browser

Is there a straightforward method to display the command-line output of a grunt task in a browser? Essentially, I want to showcase the input and/or output of a command line process within a browser window. While I am aware that I could develop a custom app ...

Using Python to convert a data frame into a nested dictionary

Currently, I have a dataframe structured like this: day account_id balance 2022-11-01 ncw8y7 1.000000 2022-11-02 ncw8y7 1.000424 My goal is to convert it into a nested dictionary format where the first level represents the acco ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

What is the best way to elegantly display a block containing background and text using Angular and ngAnimate?

I'm a beginner when it comes to JavaScript and Angular. I am attempting to use ng-show and ng-hide for my background and text elements. However, I am experiencing an issue with my text: It smoothly hides, but when it is shown again, the text appears b ...

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

Utilize AJAX to parse an HTML Table retrieved from an ASP page and extract targeted cell data

Within our work intranet, there exists an ASP page that retrieves data from a variety of sensors. This data is organized in a table format with multiple rows and columns. It struck me as interesting to showcase some of these outputs on our department&apos ...

Assign Attribute to a Different Data Transfer Object

I have a query regarding my nestjs project - is it possible to assign a value Attribute to another Dto? Specifically, I'm looking to assign idData to the id in IsUniqueValidator. I attempted the following code but it resulted in 'undefined&apos ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable. arr=[{ "name":"f ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

Ajax request (with Spring) causing HTTP error 415Charsets deems invalid

My server doesn't receive a response when I send an Ajax request. PUT request: function modifyData() { var item={ id:idNum.replace('edit',''), data:newData }; console.log(item); ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...

Adding colors dynamically upon page reload with javascript and jQuery

I have created an array of colors and am attempting to use colors.forEach inside the ready function to call addBox for each color in the array. My goal is to ensure that all the colors are added when the page is reloaded. Please let me know if you require ...

What is the best way to update placeholders in Angular 8+?

I have a collection of items: a = ['apple', 'mango', 'grape', 'papaya', 'banana', 'cucumber']. An input element is present with a placeholder stating select from fruits (the array elements should ...