Transforming a dynamic string into JSON with the power of javascript

I am working with an API that generates responses in the form of a dynamic array of strings, like the example below:

var arr = ["Request.name","Request.name.first","Request.name.first.last"]; //response 3

My goal is to dynamically convert this array into an array of JSON objects structured like this:

var arrayOfObjects = [ 
               { 
                 "Request": {
                 "name":val 
                 }
               } //converted from arr[0]
            ,{ 
                 "Request": {
                  "name":{
                   "first":val
                  }
                 }
              } //converted from arr[1] 
            ,{ 
                 "Request": {
                  "name":{
                   "first":{
                     "last":val
                   }
                  }
                 }
               } //converted from arr[2] 
        ];

and so on...

Do you think this conversion process is possible?

Answer №1

If you're looking to convert a dot-separated string into a deeply nested object, one approach is to create a function that handles this transformation and then apply it to an array of strings. My method is iterative in nature, but it could potentially be implemented recursively as well.

var inputArray = ["Request.method","Request.path.url","Request.body.payload"];

function convertStringToObject(str) {

    return str.split('.').reduceRight((nestedObj, key, i, arr) => {

        if (i === arr.length - 1) {
            nestedObj = {[key]: 0};
        } else {
            nestedObj[key] = Object.assign({}, nestedObj);
            Object.keys(nestedObj).forEach(k => {
                if (k !== key) delete nestedObj[k];
            });
        }

        return nestedObj;

    }, {});

}

const arrayOfNestedObjects = inputArray.map(convertStringToObject);

console.log(arrayOfNestedObjects);

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

What is the reason for the svg animateTransform only being triggered on the initial item?

When hovering over the first item, the animations for the others would also trigger. However, when hovering over the second item, the other items wouldn't work. How can I ensure that each item's animation triggers one by one? body { displa ...

Angular library is being excluded from the R.js optimizer process

I'm encountering difficulties when trying to optimize an Angular project with the r.js optimizer. Everything works smoothly when I use grunt-requirejs for optimization, but as soon as I attempt to exclude Angular from the build, I encounter an error ...

Resolving Problem with Replacing Values in Pandas JSON to CSV Conversion

I'm a beginner in Python and struggling to find a solution to my query (apologies if I'm not framing it correctly). I am currently working on converting a JSON file to a CSV file. One of the columns in the file contains values enclosed within sq ...

Menus that mimic the style of Google Translate's select options

I'm looking to design an HTML select menu using CSS in a similar fashion to Google Translate's style on Google Translate. I've searched for tutorials online, but they all involve jQuery. Is there a way to achieve something similar using only ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

Creating Conditional Connections in jsPlumb

Attempting to establish connections between nodes based on specific rules, such as: The "API request" endpoint is restricted from connecting to any node except "Initiate Call". The "Failed" endpoint cannot be linked to "Play Audio", and so forth. Below ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

Modify the REST request information according to the data retrieved from the preceding step's response

Currently, I am delving into the realm of test automation and attempting to utilize response values as inputs for the next request. However, a major roadblock I have encountered is that the response contains a dynamic list that can vary in length. Below i ...

How can images from a dynamic table be converted to base64 format in Vue.js and then sent in a JSON file?

Hello everyone, I'm facing an issue with a dynamic table where I need to add multiple rows, each containing a different image. I attempted to convert these images to base64 format and save them in a JSON file along with the table data. However, the pr ...

The Javascript array contains information, but its length is currently empty

UPDATE: It seems that I misunderstood how promises work, leading to a synchronization issue. I mistakenly assumed that ".then" waits for the promise to resolve, which is not the case. An unusual error has cropped up that has me stumped. I'm puzzled ...

What is the most efficient way to restrict multiple input fields, each using v-model, to only accept numeric values in Vue.js without duplicating code for every input field?

I have several input fields in Vue.js that I want to restrict to only accept numbers. I want to prevent users from entering any characters except digits from 0-9. I managed to achieve this successfully with a solution that is resistant to copy-paste: C ...

Can you provide some straightforward instances of single-axis zooming using d3?

I'm interested in creating a single-axis zoom for d3's zoom behavior. Are there any straightforward examples that demonstrate how to achieve this? I came across Mike Bostock's example, but I found it a bit complex to grasp. Here is the code ...

"Organizing Your Content: A Guide to Grouping Information under Specific

How can I organize content under different headings? I am using two methods to retrieve data: 1. axios.get('/api/get/headers') 2. axios.get('api/get/contents') I am struggling with how to properly structure this, especially since the ...

What is the best way to create floating text that appears when clicked, similar to the mechanics

https://i.stack.imgur.com/nRKG1.jpg Upon clicking the "big cookie" in my game, a popup appears displaying the number of cookies earned (like +276.341 septillion in this image). The popup slowly moves upward and then fades out. I successfully incorporated ...

Which is better for narrowing object property types: using dot notation or object literal notation?

Is there a reason why type narrowing by assignment behaves differently based on whether we use dot notation or object literal notation? Below are two examples to illustrate this discrepancy. type MyObj = { x?: number | string } let obj1: MyObj = {} obj1.x ...

The jQuery scrollTop feature seems to be malfunctioning

My code is causing an error that I don't understand. Any help would be appreciated... I'm getting the following error message: Property does not exist on type '.js--section-plan'.ts(2339) when I hover over the offset() in vscode $(&apos ...

Connect this - initiate the removal of an item

I am seeking assistance from more experienced colleagues to help me understand the code below and implement it in my App. The main objective is to trigger a REDUX action from a button, which will delete an item from a database. Here is the code that curr ...

Tips for preventing a component from updating state prior to data retrieval?

I have a specific scenario where I am working with a page that consists of two components. In this setup, I am retrieving data from the root component and passing it to the child component using the react-redux library. However, I encountered an issue wher ...

Using Golang to encode JSON for parsing in JavaScript

I am working with a struct that looks like this: type User struct { Login string `json:",string"` PasswordNonce Nonce `json:",string"` PasswordHash HashValue `json:",string"` CreatedOn time.Time `json:",string"` Email ...