Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service.

Current JSON:

{
    "specifiers": [{
        "value": "test",
        "type": "text",
        "label": "Brand ID"
    }, {
        "value": "test",
        "type": "text",
        "label": "Program ID"
    }]
}

Desired Output:


{
    "specifiers": {
        "Brand ID": {
            "text": {
                "value": "test",
                "type": "text"
            }
        },

        "Program ID": {
            "text": {
                "value": "test",
                "type": "text"
            }
        }
    }
}

I have attempted to iterate through the existing JSON data using loops, but am struggling with how to properly use the values as keys. I believe I may need to utilize Object.keys or Object.values, but I am unsure of how to access specific values based on their corresponding keys.

Example Format:

        "[label]": {
            "[type]": {
                "value": [value],
                "type": [type]
            }
        }

Answer №1

function updateData({info}) {
  return { info: info.reduce((obj, {name, category, value}) => ({...obj, [name]: { [category]: { category, value } } }), {}) }
}

const database = {
    "info": [{
        "value": "12345",
        "category": "number",
        "name": "Product ID"
    }, {
        "value": "Example Name",
        "category": "text",
        "name": "Product Name"
    }]
}

console.log(updateData(database))

Answer №2

Here's a simple solution using the reduce method:

const updatedSpecifiers = existingJSON.specifiers.reduce((acc, spec) => {
  acc[spec.label] = {
      [spec.type]: {
        type: spec.type,
        value: spec.value,
      },
    };
  
  return acc;
}, {});

const modifiedJSON = { specifiers: updatedSpecifiers };

Answer №3

In order to achieve this, you can utilize the #Array.reduce method as shown in the code snippet below.

let data = {
  "items": [{
    "name": "apple",
    "type": "fruit",
    "color": "red"
  }, {
    "name": "banana",
    "type": "fruit",
    "color": "yellow"
  }]
}
const result = data.items.reduce((result, item) => {
  const {
    name,
    type,
    color
  } = item
  result[name] = {};
  result[name][type] = {
    color,
    type
  };
  return result;
}, {});
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

Tips for deleting the displayed URL during a web page print in PHP

Is there a way to remove the URL from a page when printing using PHP? I want to achieve this without requiring my clients to change their browser settings. Any assistance would be greatly appreciated! ...

The set command is failing to save data in the JSON file

One of my new commands, known as "muterole", includes various subcommands. Here's how the muterole command is structured: @commands.group(aliases=['mr']) @commands.has_permissions(manage_roles=True) async def muterole(self, ctx): if ctx. ...

retrieving form data from a submit button using objects in PHP

I am using objects to fetch a form (including a submit button) from another page. However, I am struggling to extract the POSTED information from that submit button and believe that AJAX might be necessary. Here is an example: Page 1 initiates a call to ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

Ensuring AngularJS ui-router/app waits for $http data to avoid Flash of Unstyled Content (FOUC)

My question or situation pertains to the states defined in my AngularJS application. Here is an example of how I have them structured: $stateProvider .state('myApp', { abstract: true, template: '& ...

Displaying TypeScript issues across the entire project in WebStorm allows for a comprehensive overview

Is it possible to have Webstorm consistently report all TypeScript errors across an entire project without having to open each individual file? I prefer using the language service for performance reasons rather than running tsc as a task. I've notice ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

Managing PHP and AJAX: Strategies for handling and transmitting error responses

There are three main components involved in this process: An HTML form The AJAX connection that transmits the form data and processes the response from the PHP script The PHP script, which evaluates the data received, determines if it is valid or not, an ...

Jquery Not Responding to HasChanged Function

I am a beginner and looking for some guidance. I am attempting to develop a single page app using Jquery and AJAX, but unfortunately nothing seems to be working; no errors or any other indication. There are three hyperlinks with hrefs: #/main, #/second, # ...

Sending an object from Rails to Javascript

My MapsController is def show @outlet=OUtlet.all render 'maps/map' end In the view page map.html.erb, I iterate through each outlet to display their latitude and longitude: <% @outlet.each do |product| %> <%= product.latitu ...

angular2 fullCalendar height based on parent element

Currently, I am using angular2-fullcalendar and encountering an issue with setting the height to 'parent'. The parent element is a div but unfortunately, it does not work as expected. The navigation bar appears fine, however, the calendar itself ...

Clipanion is unable to fulfill requests

I followed the official Clipanion documentation for creating a CLI tool () and even cloned an example from here - https://github.com/i5ting/clipanion-test, but I'm facing issues when trying to execute my commands. It seems like I might be struggling ...

Converting Java String to JSONObject in Android: Troubleshooting JSONP issue

Here is the code snippet I am working with: String json = request.excutePost("http://192.168.1.42:3000/login_client",urlParameters); JSONObject jsonObj = new JSONObject(json); The error displayed in logCat is as follows: org.json.JSONException: Value ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Retrieve the chosen identification from a dropdown menu (select box) with jQuery

I've been on a quest to find a solution for extracting the id from a selected option in a dropdown list. After extensive research, I stumbled upon this helpful resource: Get selected text from a drop-down list (select box) using jQuery I attempted t ...

Assign the ngClick event handler to the capturing phase

Can the ngClick event handler be configured to work in the capturing phase, as discussed in this informative article? I am interested in stopping events from propagating down to child elements and then back up again when a specific condition is met for t ...

I'm encountering a status 415 error when trying to post to the Spotify API for tokens. Is there something I'm

My approach to interfacing with their API for the Authorization Code Flow is as follows: class func obtainAuthTokenPackage(authCode: String) throws { //Initiate a request var request = URLRequest(url: Gimme.theSpotify.urlFor(endpoint: .requestingT ...

Serialization of ISO8601 dates with a JAX-RS client in a container setting

I am currently working on a project that involves utilizing a JSON REST API with a POST /items endpoint. This specific endpoint requires an object structure like: {"name": "item_name", "timestamp": "2018-01-01T01:01:01.001"} In order to interact with thi ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...