Looking for a way to efficiently add multiple value inputs to a JSON object using jQuery or JavaScript?

Here is the HTML input tag code I am working with:

<form id="info">
    <input id="A" name="A" type="hidden" nodetye="parent" value="A">
    <input id="A1" name="A1" type="text" nodetype="child" value="a1val">
    <input id="A2" name="A2" type="text" nodetype="child" value="a2val">
    <input id="B" name="B" type="hidden" nodetye="parent" value="B">
    <input id="B1" name="B1" type="text" nodetye="child" value="B1">
    <input id="B2" name="B2" type="text" nodetye="child" value="B2">
<form>

I am using jQuery to pass values as follows:

function writeJSONfile() {
    var obj = {};
    $("form#info :input").each(function(){
        obj[this.id] = $(this).val();
    });
    var json = JSON.stringify(obj);
    alert("check"+json);
}

The current result is:

{"A":"A","A1":"a1val","A2":"a2val","B":"B","B1":"b1val","B2":"b2val"}

However, my expected result is:

{"A":{"A1":"a1val","A2":"a2val"},"B":{"B1":"b1val","B2":"b2val"}}

You can analyze and edit the JSON data using an online json editor. Thanks in Advance

Answer №1

The issue you are encountering stems from the lack of code that differentiates values like 'A', 'B' and 'A1', 'B1', etc. To resolve this, all you need to do is:

  • Define a variable that points to the object where the property should be included &
  • Add a simple conditional check using an if statement to control the execution flow.

Example:

/* ----- JavaScript ----- */
function writeJSONfile() {
  var
    /* Initialize an object. */
    obj = {},
    
    /* Declare a variable that references the current object (initially → obj). */
    ref = obj;
    
  /* Loop through each input element. */
  $("form#info :input").each(function() {
    /* Store the id of the input element. */
    var id = this.id;
    
    /* Verify if the nodetype attribute value is 'parent'. */
    if (this.getAttribute("nodetype") == "parent") {
      /* Create a new object at the property and update ref to point to it. */
      ref = obj[id] = {};
    }
    else {
      /* Assign the input's value to the referenced object. */
      ref[id] = $(this).val();
    }
  });
  
  /* Convert the object to a JSON string and return it. */
  return JSON.stringify(obj);
}

/* Generate and display the output. */
console.log(writeJSONfile());
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="info">
  <input id="A" name="A" type="hidden" nodetype="parent" value="A"/>
  <input id="A1" name="A1" type="text" nodetype="child" value="a1val"/>
  <input id="A2" name="A2" type="text" nodetype="child" value="a2val"/>
  <input id="B" name="B" type="hidden" nodetype="parent" value="B"/>
  <input id="B1" name="B1" type="text" nodetype="child" value="b1val"/>
  <input id="B2" name="B2" type="text" nodetype="child" value="b2val"/>
</form>

Answer №2

Implemented some adjustments to the management of classes and ids. This function offers a swift and straightforward solution for your issue.

I trust this meets your requirements. Feel free to reach out if you need further explanation or assistance with an improved approach.

function generateJSONFile() {
  var obj = {};

  $(".main").each(function() {
    var mainId = this.id;
    obj[this.id] = {};
    $("input").each(function() {
      if ($(this).hasClass(mainId)) {
        obj[mainId][this.id] = $(this).val();;
      }
    })
  });
  var json = JSON.stringify(obj);
  alert("check" + json);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="info">
  <input id="A" class="main" name="A" type="hidden" nodetye="parent" value="A">
  <input id="A1" class="A" name="A1" type="text" nodetype="child" value="a1val">
  <input id="A2" class="A" name="A2" type="text" nodetype="child" value="a2val">
  <input id="B" class="main" name="B" type="hidden" nodetye="parent" value="B">
  <input id="B1" class="B" name="B1" type="text" nodetye="child" value="B1">
  <input id="B2" class="B" name="B2" type="text" nodetye="child" value="B2">
  <form>
    <button onclick="generateJSONFile()">Run</button>

Answer №3

Give this a shot:


   function writeToJSONNode() {
       var object = {};
       var reference = object;
       $("form#info :input").each(function () {
           var id = this.id;
           if ($(this).attr("nodetype")==="parent") {
               object[id] = {};
               reference = object[id];
           } else
               reference[id] = $(this).val();
       });
       console.log(JSON.stringify(object));
    //    alert(JSON.stringify(object));
    //    return JSON.stringify(object);
}}

I'm using the attribute name "nodetype" for verification.

Answer №4

To update the obj object, you need to locate all inputs with the attribute nodetype set to parent. For each of these inputs, use their id as a key in the object and assign an empty object as its value. Then, go through all input elements with nodetype set to child, and add each id-value pair to the object where the id is the key and the input box value is the value.

function writeJSONfile() {
  var obj = {};
  $('form#info :input[nodetype=parent]').each(function(){
    obj[this.id] = {};
  })
  $("form#info :input[nodetype=child]").each(function(){
    if(!(this.id[0] in obj))
      obj[this.id[0]] = {};
    obj[this.id[0]][this.id] = $(this).val();
  });
  var json = JSON.stringify(obj);
  console.log(json);
}
writeJSONfile();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="info">
  <input id="A" name="A" type="hidden" nodetype="parent" value="A">
  <input id="A1" name="A1" type="text" nodetype="child" value="a1val">
  <input id="A2" name="A2" type="text" nodetype="child" value="a2val">
  <input id="B" name="B" type="hidden" nodetype="parent" value="B">
  <input id="B1" name="B1" type="text" nodetype="child" value="B1">
  <input id="B2" name="B2" type="text" nodetype="child" value="B2">
<form>

Answer №5

function createJSONfile() {
  var data = {};
  $(".main").each(function() {
    var mainId = this.id;
    data[mainId] = {};
    $("."+mainId).each(function() {
      data[mainId][this.id] = $(this).val();      
    })
  });
  console.log(JSON.stringify(data));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="info">
  <input id="A" class="main" name="A" type="hidden" nodetye="parent" value="A">
  <input id="A1" class="A" name="A1" type="text" nodetype="child" value="a1val">
  <input id="A2" class="A" name="A2" type="text" nodetype="child" value="a2val">
  <input id="B" class="main" name="B" type="hidden" nodetye="parent" value="B">
  <input id="B1" class="B" name="B1" type="text" nodetye="child" value="B1">
  <input id="B2" class="B" name="B2" type="text" nodetye="child" value="B2">
  <form>
    <input type="button" onclick="createJSONfile()" value="Generate JSON">

Answer №6

Follow this format for successful execution:

function createJSONfile() {
debugger;
    var obj = {};
    var children = {};
    $("form#info :input").each(function(){
    var parent = this;
    if(parent.getAttribute("nodetype")=="parent"){
        obj[parent.id] = {};
          var nexts = $(parent).nextAll();
          for(let i=0;i<nexts.length;i++){
          if(nexts[i].getAttribute("nodetype")!="child"){
            break;
            }else{
            obj[parent.id][nexts[i].id] = $(nexts[i]).val();
            }
          }
        }
    });
    var json = JSON.stringify(obj);
    alert("check"+json);
}
createJSONfile();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="info">
      <input id="A" name="A" type="hidden" nodetype="parent" value="A">
      <input id="A1" name="A1" type="text" nodetype="child" value="a1val">
      <input id="A2" name="A2" type="text" nodetype="child" value="a2val">
      <input id="B" name="B" type="hidden" nodetype="parent" value="B">
      <input id="B1" name="B1" type="text" nodetype="child" value="B1">
      <input id="B2" name="B2" type="text" nodetype="child" value="B2">
    <form>

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

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Local variables in AngularJS across multiple Angular applications

Looking for a method to retain a local variable not affected by path or angular app changes. Attempted using $window.localStorage.set and get item, rootScope, and $window.variable with no success. ...

Design: A stationary text box positioned on the left side alongside a selection of scrollable MDL cards on the right

I'm currently experiencing a challenge with adjusting the text on two specific pages. On one side, there is a box with text, while on the other are two MDL cards displaying dialogues. The trouble arises when I try to set a fixed position for the text ...

Showing data in a grid format on a webpage

I created a Java program that generates an array list with values such as Hi, Hello, How, Are, You, Me, They, and Them. In addition, I developed a basic controller to convert these values into JSON format and display them on localhost:8090/greeting like t ...

Include a new class in the classList of an element at a specific index

Is it possible to add a class to a specific position in order to maintain a certain order, especially when it goes against the logic that targets the class based on its position? link.closest('item').classList.add('c-class') // Contrad ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

What steps can be taken to resolve the issue of Ajax not retrieving any data from

I'm struggling to identify the error in this code. I have created a search bar and implemented AJAX to automatically fetch data. Here is the HTML file: <!DOCTYPE html> <html> <head> <title></title> <script ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

keep the color of the link after clicking until a different link is clicked

At the bottom of every post on my website, there are 3 buttons: "Written By", "Related Post," and "In This Category": SoCatchy! I'm looking to have each button change color when clicked, and stay that way until another link is clicked. Here is the c ...

Loading a Component in React (Next.JS) Once the Page is Fully Loaded

After implementing the react-owl-carousel package, I encountered an error upon refreshing the page stating that "window is not defined." This issue arises because the module attempts to access the window object before the page has fully loaded. I attempted ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...

Avoiding the insertion of styles into the HEAD section when using Webpack MiniCssExtractPlugin in combination with Create React

Currently, I am utilizing create-react-app to develop a component library with Storybook JS. The ultimate goal is to release an NPM package containing these components for use in various projects. Within this library, SASS is employed, complete with global ...

The issue with MVC4 and Ajax requests for converting image ByteArrays appears to be problematic

I am attempting to change an image in my View with a click event. However, when the controller returns a byte array, the original image is replaced with an empty one. Below is the code from my Controller: [HttpPost] public byte[] GetSelectedI ...

Is there a way to align the line under the hyperlinks to match the text size using CSS?

<div className={styles.container}> <ul className={styles.links}> <li className={styles.link}> <a href="/">Home</a> </li> <li className={styles.link}> <a href="/portfolio& ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

Looking for a solution to a problem with your vertical CSS/jQuery dropdown menu

My web app features a vertical CSS menu that is working correctly except for one minor issue. When I mouse out on all elements with the class a.menutoggle, the last dropdown menu remains open. I am struggling to find a solution to hide it. Can someone plea ...