Guide on transforming a list of fields into a JSON object

I am looking for a solution to convert my list of fields, stored as a string, into a JSON object. The fields are listed as follows:

[
"Container.Description",
"Container.Groups.12.Users.11.Name",
"Container.Groups.12.Users.12.Name",
"Container.Groups.13.Users.21.Name",
"Container.Groups.13.Users.22.Name"
]

The desired output should be in the following JSON format:

{
  "Container": {
    "Description": "",
    "Groups": [
      {
        "12": {
          "Users": [
            { "11": { "Name": "" }},
            { "12": { "Name": "" }}
          ]
        }
      },
      {
        "13": {
          "Users": [
            { "21": { "Name": "" }},
            { "22": { "Name": "" }}
          ]
        }
      }
    ]
  }
}

If anyone can assist with converting this code into TypeScript or C#, I would greatly appreciate it. Thank you in advance!

Answer №1

While this may not be the most elegant solution, it does get the job done...

    processData(inputData: string[]) {
        const result = {};

        inputData.forEach(item => this.updateObject(result, item));

        return result;
    }

    private updateObject(currentObj: { [key: string]: any }, value: string) {
        const keyArray = value.split('.');
        let objPointer = currentObj;

        for (let i = 0; i < keyArray.length; i++) {
            const key = keyArray[i];

            // If the key exists
            if (objPointer[key]) {
                objPointer = objPointer[key];
                continue;
            }

            // If the key does not exist:
            // This is the final key
            if (i === keyArray.length - 1) {
                objPointer[key] = '';
            } else {
                // This is not the final key
                objPointer[key] = {};
                objPointer = objPointer[key];
            }
        }
    }

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

Contrast the validation process for a dropdown menu containing times in AM/PM format

I have a total of 4 drop-down menus, each designated for specific intervals of time during the day. The following is the code snippet for these drop-downs: <asp:DropDownList ID="DDL_TimeFromMon" runat="server"> &l ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Exploring the detection of changes in variables using Aurelia

Is it possible to track changes to a variable using aurelia? While I know that I can detect changes in a variable's type using @observable, I am curious if it is possible to monitor changes in a variable's value, for example from a = 3 to a = 4, ...

Is it possible to retrieve information from a json file?

I am looking to extract specific elements from a JSON response fetched using the YouTube API. Here is an example of the response I receive in my script: { "version": "1.0", "encoding": "UTF-8", "feed": { // Details of the feed... } } My goal ...

Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario. private createRowData() { const rowData: any[] = []; this.http .get(`/assets/json/payment.json`) .toPromise() .then(r ...

Error: Virtual script not located; possibly absent <script lang="ts" / "allowJs": true / within the jsconfig.json.volar

https://i.sstatic.net/dFaVQ.png I noticed an error in my footer component in VueJs (TypeScript template) as depicted by the image showing blue squiggly lines. ...

Can you identify the specific syntax for a 'set' function in TypeScript?

I have a TypeScript function that looks like this: set parameter(value: string) { this._paremeter = value; } It works perfectly fine. For the sake of completeness, I tried to add a type that specifies this function does not return anything. I experimen ...

What is the best way to switch from using AsyncTask to Retrofit in order to retrieve data from a WCF Webservice

I am currently utilizing a WCF webservice to retrieve SQL Server database data in JSON format for an Android application using AsyncTask. Here is the code snippet: public class FetchInfo extends AsyncTask { private String year = "94"; private St ...

Reading a 500KB JSON file within an Android operating system

Looking for a quicker method to parse a 500KB JSON file with the following structure: { "response": { "code": 0, "msg": "OK", "searchparameter": { "bikes": { … }, "cars": { "a":{ ...

Is there room for improvement in the way I handle concurrency?

Recently, I've delved into the world of multi-threading in my code and would love some feedback on a specific part. This particular section deals with delivering video samples from a buffer that is constantly being filled by a stream parser running i ...

Is there a way to change a typescript enum value into a string format?

I'm working with enums in TypeScript and I need to convert the enum value to a string for passing it to an API endpoint. Can someone please guide me on how to achieve this? Thanks. enum RecordStatus { CancelledClosed = 102830004, Completed = ...

Spring 4.0.x is returning a HTTP/1.1 error code 406 Not Acceptable in response to a JSON

Currently, I am utilizing Spring 4.0.5.RELEASE and Spring MVC using only Java Config Within my pom.xml file, I have the following dependency: <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper- ...

Issue with Android: JSONObjects are only able to parse the last object within the file

I am encountering an issue with a json file that is structured like this (please note that the actual file has no whitespace): { "main": [ { "sections": [ "sec1", "sec2" ], "t ...

Pause for a few moments prior to initializing Bootstrap and Angular 2

I am currently developing a space/gravity game using Angular 2, and I am looking to incorporate a splash screen before the main menu component is loaded. I believe that the easiest approach would be to utilize the pre-bootstrapped contents of the index.ht ...

Using Google's PageSpeed API with the .NET framework

I have created a basic C# program for conducting a PageSpeed evaluation on a specified website utilizing the Google.Apis.Pagespeedonline.v2 nuget package. The setup process is quite straightforward, and I have a variable designated for the URL inputted in ...

Clone a task or project in Asana

How can I duplicate an existing Asana task or project? We have established templates to streamline our workflow for new orders. The goal is to centralize all paperwork that comes in, including tasks in Asana. The most convenient option would be to replic ...

What is the best method to extract pictures from "Google Images" by utilizing the custom search API when the control panel restricts users to inputting only website URLs for searching?

I have been attempting to utilize the Google Custom Search API in order to retrieve images, but unfortunately I am not seeing the same results as those displayed in Google Images. When I access the custom search control panel, it instructs me to add specif ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Populate a cell in a dataframe with an array of values

Update : After reworking and reflecting on this, I believe the question is better formulated as follows. I have been struggling with this issue for quite some time without success. To illustrate what I am trying to achieve, here is an example: Beginning ...

What is the reasoning behind certain libraries offering methods that perform identical tasks, but one in synchronous and the other in asynchronous context?

It's common for libraries to provide two methods that perform the same task, with one running asynchronously and the other synchronously. For example, unlink in fs/promises is similar to unlinkSync in fs; also, compare, compareSync, hash, and hashSyn ...