Switch up the format of a JSON data structure using JavaScript

I am facing an issue with converting a JSON structure into another format. I would appreciate any help or suggestions on this matter. I have tried different methods and alternatives for conversion, but I am still searching for the most efficient way to accomplish it.

// ORIGINAL
{
  Monday: {
    Transactions: [
      {Amount: 100, Status: "Cleared"},
      {Amount: 200, Status: "Pending"},
      {Amount: 300, Status: "Failed"}
    ]
  },
  Tuesday: {
    Transactions: [
      {Amount: 700, Status: "Cleared"},
      {Amount: 800, Status: "Pending"},
      {Amount: 900, Status: "Failed"}
    ]
  },
  Wednesday: {
    Transactions: [
      {Amount: 400, Status: "Cleared"},
      {Amount: 500, Status: "Pending"},
      {Amount: 600, Status: "Failed"}
    ]
  }
}

// EXPECTED OUTPUT
{
  Cleared: {
    Transactions: [
      {Amount: 100, Day: "Monday"},
      {Amount: 700, Day: "Tuesday"},
      {Amount: 400, Day: "Wednesday"}
    ]
  },
  Pending: {
    Transactions: [
      {Amount: 200, Day: "Monday"},
      {Amount: 800, Day: "Tuesday"},
      {Amount: 500, Day: "Wednesday"}
    ]
  },
  Failed: {
    Transactions: [
      {Amount: 300, Day: "Monday"},
      {Amount: 900, Day: "Tuesday"},
      {Amount: 600, Day: "Wednesday"}
    ]
  }
}

Answer â„–1

Here is a sample code snippet for processing transactions based on their status:

const input = {
    Monday: {
        Transactions: 
        [{Amount: 100, Status: "Cleared"},
        {Amount: 200, Status: "Pending"},
        {Amount: 300, Status: "Failed"}]
  },
  Tuesday: {
        Transactions: 
        [{Amount: 700, Status: "Cleared"},
        {Amount: 800, Status: "Pending"},
        {Amount: 900, Status: "Failed"}]
  },
  Wednesday: {
        Transactions: 
        [{Amount: 400, Status: "Cleared"},
        {Amount: 500, Status: "Pending"},
        {Amount: 600, Status: "Failed"}]
  }
}

const output = {
    Cleared: {
        Transactions: []
    },
    Pending: {
        Transactions: []
    },
    Failed: {
        Transactions: []
    }
}

for (const day in input) {
    for (const transaction of input[day].Transactions) {
        const status = transaction.Status;
        output[status].Transactions.push({
            Amount: transaction.Amount,
            Day: day
        });
    }
}

Answer â„–2

If you want to effectively group data, the best method to use is the reduce function.

const givenData = { Monday: { Sales: [{Amount: 100, Status: "Completed"}, {Amount: 200, Status: "Pending"}, {Amount: 300, Status: "Failed"}] }, Tuesday: { Sales: [{Amount: 700, Status: "Completed"}, {Amount: 800, Status: "Pending"}, {Amount: 900, Status: "Failed"}] }, Wednesday: { Sales: [{Amount: 400, Status: "Completed"}, {Amount: 500, Status: "Pending"}, {Amount: 600, Status: "Failed"}] }};

const results = Object.entries(givenData).reduce((accumulator,[Day, values])=>{
    values.Sales.forEach(({Amount, Status})=>{
        accumulator[Status] ??= {Sales:[]};
        accumulator[Status].Sales.push({Day, Amount});
    });
    return accumulator;
},{});

console.log(results);

Answer â„–3

To achieve this, you can implement a nested forEach loop:

const data = {Monday: {Transactions: [{Amount: 100,Status: "Cleared"},{Amount: 200,Status: "Pending"},{Amount: 300,Status: "Failed"}]},Tuesday: {Transactions: [{Amount: 700,Status: "Cleared"},{Amount: 800,Status: "Pending"},{Amount: 900,Status: "Failed"}]},Wednesday: {Transactions: [{Amount: 400,Status: "Cleared"},{Amount: 500,Status: "Pending"},{Amount: 600,Status: "Failed"}]}}

const result = {
    Cleared: {Transactions: []},
    Pending: {Transactions: []},
    Failed: {Transactions: []}
}

Object.keys(data).forEach((day) => {
    data[day].Transactions.forEach((transaction) => {
        result[transaction.Status].Transactions.push(transaction)
    })
})

console.log(result)

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

Is there a way to tell when a mouse is no longer hovering over an element?

Can someone explain to me how to detect when a mouse stops hovering over an element using either Javascript or CSS? I am working on an animation where the background changes color when hovered over by a mouse, but I also want to add another animation for ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Upon clicking the collapse button, the collapsed element briefly appears before its height value is reset to empty in the element's style

Check out this code snippet: <!-- Expand buttons --> <div> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExa ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

Converting JSON to an unnamed object using JSON.NET

I am facing an issue with deserializing an object using JSON.NET. The current structure of the object I am working with is causing problems. The format of my object is as follows (I want to pass a list of objects) [ { "ID": "Concurrent User", "Fi ...

When will the javascript file fire if it has this implementation?

Can someone help me make sense of this jquery snippet? (function( window, undefined ) { //All the JQuery code is included here ... })(window); I'm curious, if a .js file is loaded in a page using the <script> tag, at what point does it ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Verify if function is returning sessionStorage using jest

Recently, I've been working on creating a jest test for the function below that sets a sessionStorage entry: /** * @desc create authenticated user session * @param {String} [email=''] * @param {Date} [expires=Date.now()] * @param {St ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

Unraveling encoded characters in URLs using Node.js

When I try to send a cookie back using res.cookie(JSON.stringify({bar: "baz"}), the value that I get in return is %7B%22bar%22%3A%22baz%22%7D. How can I decode this in a Javascript setting like node.js? ...

Error in vue.js: Unable to call this.$emit as it is not a function

export default { mounted() { setTimeout(function() { this.$emit('onLoad') }, 4000); } } //views/Load.vue I want to redirect to another page after the page has been accessed for 4 seconds. <template> <d ...

What is the method for invoking Gruntfile tasks programmatically using code?

Is there a way to access and execute tasks from Gruntfile in my code? Appreciate any help! ...

Integrate MongoDB with my JSON data

"Title": "Anti-Mage", "Url": "antimage", "ID": 1, "Lore": "The legend of the Anti-Mage revolves around the monks of Turstarkuri and their valiant stand against the Legion of the Dead God. As invaders swept through the lower kingdoms, these asce ...

Attempting to convert PHP tables into PDF format by utilizing jsPDF-auto-table to generate a beautifully structured PDF file containing the results of a PHP query with multiple records

I'm new to stackoverflow but I find myself visiting it regularly for helpful tips. I've taken some code from the simple.html file that comes with the jsPDF auto-table plugin. However, I'm having trouble making it work with data generated by ...

Struggling to modify CSS properties for :before and :after pseudo-elements?

My current styling looks like this: section.tipos .content > div:before { background: none repeat scroll 0 0 #DDDDDD; content: " "; height: 10px; left: 32%; position: absolute; top: -10px; width: 10px; } It's working p ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

The function is not executing within the window.plugins context in the Angular/Ionic platform

Problem: I am facing an issue with storing a picture in base 64 format. The window.plugins.Base64.encodeFile method is not functioning as expected. I have successfully installed the Cordova Plugin locally and the $cordovaImagePicker is working fine. Howe ...

State in Vuex is not kept intact after redirection to another page

Inside my Vue.js application, I have created a method for logging in users. This method sends a POST request to the server with the username and password, stores the returned data in Vuex store, and then redirects the user to the home page: login: func ...