Changing HTML data into a intricate JSON structure

I need assistance with converting form-data where the field names reference a nested JSON structure into a JSON object. The initial object representing the form-data is as follows:

{
    "custom[1].a": "FIXED",
    "custom[1].b": "",
    "custom[1].c": "PROPORTIONATE",
    "custom[1].d": ""
    "custom[2].a": "FIXED2",
    "custom[2].b": "",
    "custom[2].c": "PROPORTIONATE2",
    "custom[2].d": ""
}

My goal is to convert this into an object that can be easily stringified:

"customConfiguration": [
     {
        "a": "PROPORTIONATE",
        "b": "",
        "c": "FIXED",
        "d": ""
    },
    {   "a": "PROPORTIONATE2",
        "b": "",
        "c": "FIXED2",
        "d": ""
    }]

Answer №1

Perhaps this is the solution you are seeking. If we assume that the numbers represent array indexes and are one-based, then decrementing by 1 will give you a zero-based result.

  • This code snippet iterates over all keys of the object using the reduce method, starting with an empty object

  • It replaces any occurrence of '[' with '.[', splits the key into parts where strings with '[...]' indicate array values while others represent regular properties

  • Another reduce function is applied for the right property reference, initially starting with the object obtained from the first iteration

    • It checks if the item is an array index, and if so, decrements it by 1 to make it zero-based

    • Depending on whether the next part is an array index or not, either an array or an object is returned

    • If the key is the last one in the array, it assigns the corresponding value

    • Finally, it returns the new object reference

  • The final object is then returned

var object = {
        'custom[1].a': 'PROPORTIONATE',
        'custom[1].b': '',
        'custom[1].c': 'FIXED',
        'custom[1].d': '',
        'custom[2].a': 'PROPORTIONATE2',
        'custom[2].b': '',
        'custom[2].c': 'FIXED2',
        'custom[2].d': ''
    },
    newObject = Object.keys(object).reduce(function (r, a) {
        a.replace('[', '.[').split('.').reduce(function (o, b, i, kk) {
            function isArrayIndex(s) { return /^\[\d+\]$/.test(s); }                
            if (isArrayIndex(b)) {
                b = b.match(/\d+/) - 1;
            }
            o[b] = o[b] || (isArrayIndex(kk[i + 1]) ? [] : {});
            if (i + 1 === kk.length) {
                o[b] = object[a];
            }
            return o[b];
        }, r);
        return r;
    }, {});

    document.write('<pre>' + JSON.stringify(newObject, 0, 4) + '</pre>');

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

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Parsing JSON data in a CodeIgniter PHP environment from React using AJAX

Currently, my React application is running on localhost:3000 while my CodeIgniter API is running on localhost:8000. I am attempting to send an AJAX post request and pass data in JSON format but I am unsure of how to receive it in my controller. Here is wh ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

Replacing Constants in Protractor Test

Within my configuration object, I have set up two boolean variables that are passed to a constant within my Angular application. When the page loads, these booleans are checked. If both are true, the user remains on the page. However, if one or the other ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Converting a class to a JSON object with ArraySegment

I am currently grappling with a particular issue, I am aiming to transfer a Json object using ArraySegment my JSON Data conforms to this structure {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

I'm having trouble getting the activeStyle to work properly with a <NavLink>

I'm facing an issue with setting activeStyle for the NavLink component when the URL is on the map route. Currently, when I click on a NavLink, I can navigate to the correct route, but only <NavLink to='/' is being highlighted as active. ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

Tips for generating a <span> element using the img alt tag and inserting it following the <img> element

I have a set of images with 'alt' tags and I would like to extract the 'alt' tag for each img and create a <span> + alt tag + </span> line after each image. I am unsure of how to achieve this using jQuery. The desired outpu ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

Angular 4: activating a function from a template

In my Angular 4 project, I am trying to calculate the average of some numbers. Here is a simplified version of my component: @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent { ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...

Exploring layered data through specific properties

Imagine a scenario where I have an array filled with data. Each element in this array is an object that could contain: an id some additional data a property (let's name it sub) which may hold an array of objects with the same properties (including t ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Best practices for assigning values to model field in EXT JS are as follows:

I'm facing an issue with a certain model structure: Ext.define('my.workspace.Area', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'string'}, {n ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...