Convert JSON data into the desired format

My JSON input is as follows:

  [
        {
            "date": {
                "value": "2022-05-01"
            },
            "parent": {
                "value": "Choclate"
            },
            "child": {
                "value": null,
                "filterable_value": "EMPTY"
            },
            "qty": {
                "value": 21052631.657999996,
                "rendered": "21.05M"
            }
        },
        ...
]

I am looking to transform the JSON data based on parent categories and format the child elements under each parent in a specific way. The transformation should be dynamic without hardcoding any comparisons with strings.

The desired output format of the JSON should resemble the following:

[
  {
    "Choclate": [
     {
          null: [
        {
            "2022-05-01": {
              "value": 21052631.657999996
            }
          }
        ]
      },
      {
          "ABC": [
        {
            "2022-05-01": {
              "value": 505567
            }
          }
          
        ]
      },
      ...
      
      ]
  },
  {
    "Drink":[
{
          "ABC": [
        {
            "2022-05-01": {
              "value": 882010439.286
            }
          }
          
        ]
      },
      ...
]   
  }
  ]

I have attempted to separate the parents and child values into arrays, but I've been unsuccessful so far. Please provide suggestions on how to achieve the transformation from the input JSON to the desired output JSON format.

const data =[
        {
            "date": {
                "value": "2022-05-01"
            },
            "parent": {
                "value": "Choclate"
            },
            "child": {
                "value": null,
                "filterable_value": "EMPTY"
            },
            "qty": {
                "value": 21052631.657999996,
                "rendered": "21.05M"
            }
        },
        ...
];

let uniqueparent = [...new Set(data.map(item => item['parent']['value']))];
let uniquechild = [...new Set(data.map(item => item['child']['value']))];

console.log(uniqueparent);
console.log(uniquechild);

From this point, I'm uncertain how to proceed with transforming my data into the desired JSON format.

Answer №1

This works perfectly for my needs:

const data = [
        {
            "date": {
                "value": "2022-05-01"
            },
            "parent": {
                "value": "Chocolate"
            },
            "child": {
                "value": null,
                "filterable_value": "EMPTY"
            },
            "qty": {
                "value": 21052631.657999996,
                "rendered": "21.05M"
            }
        },
        ...
];

const formattedData = data.reduce((result, el) => {
    const parentName = el.parent.value;
    const childName = el.child.value;
    const dateValue = el.date.value;
    
    if (!result[parentName]) result[parentName] = {};
    
    const parent = result[parentName];
    
    if (!parent[childName]) parent[childName] = {};
    
    const child = parent[childName];
    
    if (!child[dateValue]) child[dateValue] = el.qty.value;
    
    return result;
}, {});

console.log(formattedData);

If you specifically need an object in the "date" property:

const data = [
        {
           ...
];

const formattedData = data.reduce((resultTypes, el) => {
    const resultMap = resultTypes.resultMap;
    const resultArr = resultTypes.resultArr;
    
    const parentName = el.parent.value;
    const childName = el.child.value;
    const dateValue = el.date.value;
    
    if (!resultMap[parentName]) {
        ...
    
    return resultTypes;
}, {resultMap: {}, resultArr: []}).resultArr;

console.log(formattedData);

Answer №2

If you're looking to organize your data in a more hierarchical way, building a tree structure might be what you need. An easy example using arrays can be found here:

To enhance the functionality of this structure, consider creating a Node class with "data", "children", and "parent" variables. Then, implement a Tree class or functionality that can efficiently work with Nodes to manage elements, track them, display them in a specific format, and more.

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

Issues with posting form data in AngularJS are occurring

Here is the code I am currently using: On the Angular side vm.onSubmit = function(){ var person = vm.formData.slice(0, 1)[0]; //This line extracts the required fields from the model object which is nested in an array. $http({ ...

Ways to connect the value of one variable to multiple others

I am trying to work with two variables: masterdata and datatoedit. The masterdata variable contains an array value, while datatoedit holds an object value. My goal is to copy the first data element from masterdata into the variable datatoedit, so I attemp ...

Minimize the length of the styled-component class name in the upcoming iteration

Dealing with styled-components in Next along with React can pose a challenge when it comes to ensuring proper rendering of the styled components. To tackle this issue, Next offers the compiler.styledComponents flag within the next.config.js file like so: c ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Struggling to eliminate placeholders using regular expressions in JavaScript

In my dynamically generated table, I have some placeholders that need to be removed. These placeholders are in the format of {firm[i][j]}, where i and j are numbers. I attempted to use a regular expression in JavaScript to remove them, but it didn't ...

Utilize the asynchronous power of Morgan to quickly display your

After investing a considerable amount of time into this task, I'm uncertain about its feasibility: Creating a reverse lookup of IP addresses and logging it through morgan Express.use(Morgan(async(tokens, req, res) => { async function ip_reverse ...

When utilizing jQuery lightbox to pull data from a database using PHP/Ajax, it may require a double click the

Encountering a strange issue where I must click on specific buttons with unique IDs. These IDs are then sent through Ajax to a PHP script, which searches for corresponding entries in the database. The retrieved data is then displayed in a jQuery lightbox. ...

Ways to retrieve the data type of individual elements from a JSONix mapping file in JavaScript

After reviewing an xsd file, I used a command to generate a js file in order to export a specific element to a json file. The xsd file structure looks like this: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified ...

The call to Contentful's getAsset function resulted in an undefined value being

I am facing a challenge while trying to fetch an asset, specifically an image, from Contentful and display it in my Angular application. Despite seeing the images in the Network log, I keep encountering an issue where the console.log outputs undefined. Any ...

Receive JSON Object from AWS SQS Event

I have a AWS lamda function that reads events from an SQS FIFO Queue as shown below const CreateItemfromSQS: Handler = async ( event: SQSEvent,context: Context,callback: Callback ) => { console.log("*** New event Called ***"); var x : a ...

`Generate JSON list`

How can I properly encode an array in PHP as JSON, ensuring it includes two variables? $var = 33; $last = 44; Here are the database results: foreach($query->result() as $r) { $data[]= $r; // Fills the array with results } I am attempting to cre ...

A step-by-step guide on converting JSON data from JavaScript to C# variables

Hey there! I have a JavaScript snippet where I am sending an array to my C# file in JSON format. var r=['maths','computer','physics'] $.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r) }, function ...

Adding a new attribute-value pair to an existing json11 object in C++ - some useful tips!

For instance, I'm creating a JSON message using the code snippet below: json11::Json my_json = json11::Json::object{ { "key_val1", val1}, { "key_val2", val2}, { "key_val3", val3}, { "key_val4", val4 } }; std::string message = my_json ...

What is the best way to transfer an array made in JavaScript to a different JSP and subsequently utilize that array in a Java function within that JSP?

I have a script that needs to pass an array called "playernames" to a Java function on another .jsp. I'm looking for guidance on how to send this array to the other page and then retrieve it for my Java function. <script> function getPlayerName ...

Scrolling seamlessly within a container that is fixed in position

For hours, I've been attempting to incorporate smooth scrolling into my project with no success. The issue lies in the container where the anchor tags are located. If it's set to fixed position or absolute, none of my attempts seem to work. In ...

The toggle class feature of jQuery is malfunctioning when placed inside a different div

Hello everyone, I am currently working on a toggle effect on my webpage. However, I encountered an error when trying to move the button close to another part of the page. The button works fine if it is placed in one part of the HTML, but does not work if i ...

Leverage information from graphql API response to enhance functionality in React components

Hey there, I'm facing a little challenge that's been keeping me stuck for a while now, so any advice or guidance would be greatly appreciated! Currently working on a react app where I'm making a call to a GraphQL api using apollo. Within an ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

A guide to sketching the ellipsoid with three.js

Despite Three.js offering functions for drawing ellipses, I am in need of assistance to draw an ellipsoid instead. Can someone please help me? I have a specific requirement to draw an ellipsoid using three.js. ...

Vuejs unstyled content flash

I encountered an issue while loading a page with Vue. Initially, I am able to access variables like @{{ value }} but once the page is fully loaded, the variable becomes invisible. How can I resolve this issue? I have already included Bootstrap and all scri ...