Transforming a JSON array into variable names and values extracted from nested form data in order to refill a form

Allow me to clarify this situation. I am working with a form that is converted into nested json from grouped form elements like

<input type="checkbox" name="faults[slats][]" value="cracked"/>
<input type="checkbox" name="faults[slats][]" value="broken"/>
<input type="text" name="partsRequired[0][partDescription]"/>
<input type="text" name="partsRequired[0][size][]"/>
<input type="text" name="partsRequired[0][size][]"/>
<input type="text" name="partsRequired[1][partDescription]"/>
<input type="text" name="partsRequired[1][size][]"/>
<input type="text" name="partsRequired[1][size][]"/>

The resulting analyzed json appears as follows:

{
    faults : {
        "slats": [
            "cracked",
            "broken"
        ]
    },
    partsRequired: [
        {
            "partDescription": "Fabric Ochre",
            "size": ["1x5m", "1m", "2m"],
            "colour": "Ochre",
            "quantity": "1"
        },
        {
            "partDescription": "",
            "size": "",
            "colour": "",
            "quantity": ""
        }
    ]
}

I am looking for a way to iterate through this data and refill the form accordingly. I have a method that reconstructs the variable names and values in such a manner that it works for the first set of data 'faults'. However, I am facing difficulty when trying to implement this for the combined scenario of 'parts required'.

Please refer to the provided fiddle: http://jsfiddle.net/JyfA2/1/. When passing the array to the function, you will notice that it generates the correct data. Nevertheless, passing 'partsRequired' saves the key integer for 'partsRequired[0][size][]', which leads to providing the wrong name for finding and populating the element on the form.

How can I overcome this challenge?

Answer №1

I need to take note of several things. Firstly, what is present in your jsfiddle is not true JSON but object literal notation. There is a distinction between the two. The key difference is that with object literal notation, you can utilize dot notation (e.g., partsRequired.size) to access and modify values. In contrast, actual JSON requires passing it through a json parsing function like jQuery.

var faults = {
"slats": [
"Over tighten slats"
],
"fabric": [
"Fraying (not overlooked)"
],
"leather": [
"Scuffed / Scratched",
"Indents / Creasing"
],
"headboard": [
"Damage Upholstery"
]
}    

var partsRequired= [
{
"partDescription": "Fabric Ochre",
"size": ["1x5m","1m","2m"],
"colour": "Ochre",
"quantity": "1"
},
{
"partDescription": "",
"size": "",
"colour": "",
"quantity": ""
}
];

console.log(faults.headboard[0]);
console.log(faults.leather[0] + " & " + faults.leather[1]);

console.log(partsRequired[0].size[0]);
partsRequired[0].size[0] = 'whatever';
console.log(partsRequired[0].size[0]);

partsRequired[1].size = [];
partsRequired[1].size.push("1");
partsRequired[1].size.push("2");
partsRequired[1].size.push("3");

for(var i = 0; i < partsRequired[1].size.length; i++){
    console.log(partsRequired[1].size[i]);
}

Take a look at these examples to better understand what I mean. http://jsfiddle.net/7ZB3G/

EDIT: included code to correctly input values into the designated textbox http://jsfiddle.net/chUQV/5/

Answer №2

Check out this solution HERE

The issue at hand is the necessity for recursive parsing of the value when it is of type Object.

if (value instanceof Array || value instanceof Object) {
    ProcessData(value, varNamesArray, varValuesArray, indexKey);
}

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

Exploring the search capabilities of input fields that are disabled

Lately, I've been struggling with a search function on my table of information. The trouble started when I made the text in the table editable - now the search function refuses to cooperate. I've tried troubleshooting it from different angles, b ...

Mapping an array of strings to model field values in EXTJS

I currently work with EXT JS 4.1.1. Upon receiving a JSON response structured as follows: { values: ["A","B","C"] } I proceed to define a model in the following manner: Ext4.define('model', { extends: 'Ext4.data.model', fiel ...

Python/NumPy implementation of image thresholding through vectorization

I'm currently exploring methods to improve the efficiency of iterating through an image and splitting its properties based on a threshold. While conducting research online and consulting with fellow programmers, I learned about the concept of vectoriz ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

Can components be nested within other components using http-vue-loader?

Trying to incorporate Vue components within components without utilizing webpack for practical reasons is my current challenge. I have opted to use http-vue-loader for loading the vue files into my project. Thus far, I have successfully created vue files ...

Having trouble fetching JSON data using Ajax in Flask

I am working on creating a straightforward web application for displaying logs. The backend is powered by Python 3.4 and Flask, while the frontend consists of a simple web form with AJAX integration. Flask: import json from flask import Flask, jsonify, r ...

Click on an item in the list to remove it from the list

I am working with an object that contains multiple arrays of objects. I need help figuring out how to remove a single item from the list when clicked on. Although I know that using splice can achieve this, I'm unsure about implementing it in this spe ...

Converting a functional component into a class-based component

I am in the process of converting a functional based Component to a class-based Component and creating a PrivateAuth Component. Here is the original PrivateAuth functional Component. function PrivateRoute({ component: Component, ...rest }) { return ( ...

Navigating the missing "length" property when dealing with partial functions generated using lodash's partialRight

I've been utilizing MomentTimezone for time manipulation within the browser. My development stack includes TypeScript and Lodash. In my application, there is an accountTimezone variable set on the window object which stores the user's preferred ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Guide on creating and organizing arrays of tuples in R

How can I sort a list of tuples based on their second item? Here is an example with some pseudocode: events <- vector(mode = "list", length = 5) events[[1]] <- c(3,1.4) events[[2]] <- c(2,1.8) events[[3]] <- c(8,5.3) events[[4]] <- c(6,1.4) ...

Transferring Arrays from C++ to C#

Seeking to transfer a double array (which is actually a std::vector, but converted during transfer) from a c++ dll to a c# script in Unity. Following the method described here. I've managed to display the size of the array on my Unity console success ...

What could be causing the failure in Selenium's findElement(By.css("span:contains(string)") method?

I have been attempting to use selenium-webdriver to click on a specific element within a website, which happens to be plain text. However, when I use the following javascript code const spanElement = driver.findElement(By.css("span:contains('TEXT&apo ...

Displaying a specific section of HTML only if a certain resource bundle key is present

Working with JSF and needing to load a bundle named Extra, I have encountered an issue. <f:loadBundle basename="com.ni.lib.extra.delivery.ExtraBundle" var="extra" /> Within the variable "extra", there exists a value known as downtime_notice. To imp ...

Using TypeScript to Trigger Events in Three.js

After recently diving into Typescript, I encountered an issue when using EventEmitter from the ThreeJS library. Whenever I attempt to trigger an event: const event: THREE.EventDispatcher = new THREE.EventDispatcher(); event.addEventListener('test&apo ...

No correct sorting method was found for Java Arrays.sort()

I am currently working with an int[] array that I need to sort based on its median value. To achieve this, I first sorted the array, calculated the median, and then attempted to use a lambda expression as a comparator for sorting again. However, when I tr ...

Transfer the HTML5 FullScreen (MAP) feature onto a separate display

I'm trying to integrate a leaflet map into my AngularJS Application, but I've hit a roadblock. My goal is to move the Fullscreen feature of the Map to a second screen (if one is available), allowing users to interact with the application on the ...

Issue with jQuery AJAX call: When submitting an HTML form, control is not being returned to the calling

I am facing an issue with my HTML form where it is loaded correctly into the DOM through a jQuery ajax call. The problem arises when I submit the form data to a PHP module using another jQuery ajax call. Even though the network traffic shows that the form ...

Looking for some help with a quick jQuery mouseleave inquiry

I wrote a short JavaScript code using jQuery that allows for a ul to slide down when an image is clicked: $(document).ready(function () { $('img.menu_class').click(function() { $('ul.the_menu').slideToggle('medium'); }); }); ...

The program is encountering an error message indicating the use of an undefined constant

I'm just diving into the world of angularjs and running into some roadblocks while trying to set up a basic checklist. <html lang="en" ng-app> <body> <div ng-controller="IdController" class="id-contain"> <ul> <li ng-r ...