Converting a JSON object into a different format using TypeScript

Looking for advice on how to efficiently convert JSON data into a specific format without hardcoding any values like "root" or "Amount". I want to create a reusable function that can be used in various scenarios. Currently, I am working with TypeScript and Node.js.

Current JSON:

{
    "elements": [
        {
            "type": "element",
            "name": "root",
            "elements": [
                {
                    "type": "element",
                    "name": "Amount",
                    "elements": [
                        {
                            "type": "text",
                            "text": "1.00"
                        }
                    ]
                },
                {
                    "type": "element",
                    "name": "Discount",
                    "elements": [
                        {
                            "type": "text",
                            "text": "0.00"
                        }
                    ]
                }
            ]
        }
    ]
}

Expected Output:

{
  "root": {
    "Amount": "1.00",
    "Discount": "0.00"
  }
}

Attempt-1: Tried this approach but not satisfied:

var newJsonData = convertedXml2json.replace(/"elements": /g, "").replace(/"type": "element",/g, "").replace(/"name":/g, "").replace(/"type": "text",/g, "").replace(/"text":/g, "").replace("[", "").replace("{", "");
console.log(newJsonData);

Attempt-2: Ended up with null result:

var len = convertedXml2json.elements,
    newData = {updatedJson:[]},
    i;

for (i=0; i < len; i+=1) {
    newData.updatedJson.push([convertedXml2json.elements[i].name, convertedXml2json.elements[i].elements[i].text]);
}

Answer №1

If you already have the JSON parsed into an object, you can utilize Array.prototype.map in conjunction with Object.fromEntries to transform the outcome back to an object:

const input = {
  "elements": [{
    "type": "element",
    "name": "root",
    "elements": [{
        "type": "element",
        "name": "Amount",
        "elements": [{
          "type": "text",
          "text": "1.00"
        }]
      },
      {
        "type": "element",
        "name": "Discount",
        "elements": [{
          "type": "text",
          "text": "0.00"
        }]
      }
    ]
  }]
};
const output = Object.fromEntries(input
  .elements.map(x => [x.name, Object.fromEntries(x
    .elements.map(y => [y.name, y.elements[0].text]))]));
console.log(output);

For an alternative approach, you could make use of lodash's map and fromPairs:

// import _ from 'lodash'; 

const input = {
  "elements": [{
    "type": "element",
    "name": "root",
    "elements": [{
        "type": "element",
        "name": "Amount",
        "elements": [{
          "type": "text",
          "text": "1.00"
        }]
      },
      {
        "type": "element",
        "name": "Discount",
        "elements": [{
          "type": "text",
          "text": "0.00"
        }]
      }
    ]
  }]
};
const output = _.fromPairs(
  _.map(input.elements, x => [x.name, _.fromPairs(
    _.map(x.elements, y => [y.name, y.elements[0].text]))]));
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7bbb8b3b6a4bf97e3f9e6e0f9e6e6">[email protected]</a>/lodash.min.js"></script>

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

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

Why isn't ThreeJS camera.lookAt() working as expected? Am I missing something in my implementation?

When working with Three.js, my goal is to have a camera directed towards a specific point in 3D space. To achieve this, I attempted to use the camera.lookAt function in the following way: camera.lookAt(new THREE.Vector3(-100,-100,0)); Unfortunately, it ...

A guide on arranging and styling last names in an array in alphabetical order using JavaScript!

I created an array called moonwalkers and developed a function named alphabetizer to organize the names in alphabetical order with the last name appearing first. Although it functions correctly, I am seeking ways to enhance the code. For my reference, I ...

What's the reason behind this being Undefined? Is there a way to resolve this issue?

After loading the `empresas` in the function, when attempting to retrieve it using `console.log(this.empresas[0]);` it gives an error saying it is undefined. empresas: any; constructor(...) { this.getEmpresas(); console.log(this.empresas[0]); } getEmp ...

Show pictures directly from multipart/form-data parsers without the need to save them

Within this inquiry, the process involves saving images uploaded via multipart/form-data parsers in a temporary folder using const tempPath = req.file.path. Subsequently, these images are then transferred to a designated directory using const targetPath = ...

The attribute 'xxx' is not found within the 'Readonly<{}>' type

I am currently in the process of writing tests for a React Typescript component. App.tsx: import * as React from 'react'; import { Button } from 'react-bootstrap'; interface Igift { id: number; } interface IAppState { gifts: Igi ...

The readyState remains stuck at 1 without progressing further

Struggling to input data into an XML using javascript's open() function. The website remains stuck at readyState 1, Here is the Javascript code snippet: function addItem() { var name = document.getElementById('Iname').value; va ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

How should one properly assign an element type provided as an argument?

I'm attempting to define a type for an element passed as a parameter using React.ComponentType. import * as React from "react" type BaseType = { element: React.ComponentType } const Base = ({element: Element}: BaseType) => ( <Ele ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

sending data in JSON format from ASIHTTPRequest to Django

Hi everyone, I've reached a dead end in my search for answers on other threads, so I'm turning to this platform for help with my question. As a beginner, I hope you can bear with me if I've made any mistakes along the way. The more I read, t ...

retrieve the chosen option from the dropdown menu

Whenever I try to display the input type based on the selection from a select element, I encounter an issue Here is the select element within my view: <select id="type" name="type_id" class="form-control" required> @foreach($type as $row) & ...

Issue with Angularjs: NG-repeat and filter not functioning correctly on array

After spending the last 3 hours searching on Google and Stack Overflow, I thought this would be easy, but I'm still stuck. I have a simple ng-repeat where I need to display everything from data2 that matches the unique ID in my data1's ref_id co ...

Implementing multiple TypeScript classes with the same interface and comparing the properties of their objects

Looking to incorporate 2 classes for business logic within my application. Below is some pseudo code showcasing the use of object and string types to specify each logic: Includes interface and class declarations; interface IResult<T, E> { resul ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

When the button/link is clicked, I must dynamically create a modal popup that includes a user control

I am currently working on improving an asp.net web forms website by incorporating popup modals to display the rental rates for available equipment. The challenge arises when dealing with pages where each piece of equipment has different rates, requiring a ...

Improve the parallax effect in your React component

Do you have any tips on smoothing out the scrolling animation for a React component with a simple parallax effect? I tried using requestAnimationFrame() in vanilla JS, but it doesn't seem to work well within the React component's rendering cycle. ...

How does Express handle the req.params format?

Encountering a strange issue with req.params in Express. When accessing specific properties like res.json(req.params.paramName), it returns the expected value. But when attempting to send the entire req.params object to the client using res.json(req.params ...