0

I have list of fields as a string:

[
"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"
]

Is there a way to convert this array of fields to json object like:

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

I need this code into typescript or c#. Thanks in advance.

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82

1 Answers1

1

It maybe not a very good solution, but it indeed works...

    handleData(data: string[]) {
        const res = {};

        data.forEach(dataItem => this.changeObjectByStr(res, dataItem));

        return res;
    }

    private changeObjectByStr(currentObject: { [key: string]: any }, str: string) {
        const keyList = str.split('.');
        let usedObject = currentObject;

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

            // The key existed
            if (usedObject[key]) {
                usedObject = usedObject[key];
                continue;
            }

            // The key not exist:
            // This is the last key
            if (i === keyList.length - 1) {
                usedObject[key] = '';
            } else {
                // This is not the last key
                usedObject[key] = {};
                usedObject = usedObject[key];
            }
        }
    }

xuan
  • 11
  • 1