Home > OS >  Add element for each value of the key - JSON
Add element for each value of the key - JSON

Time:03-29

I have a form with user input and I serialize the data in JSON. What I want is that for each value of a specified key I want to add a prefix when the user should fill the input, like if the user introduce 123, the final output should be http://123, but just for one input field, not for every input field in my form.

This is my code, everything is working till I do the console log:

function convertFormToJSON(form) {
  var array = jQuery(form).serializeArray();
  var json = {};

  jQuery.each(array, function() {
    json[this.name] = this.value || '';
  });

  return json;
}
console.log(convertFormToJSON(document.getElementById("myform")));

var blah=convertFormToJSON(document.getElementById("myform")));

function addStringToValueInJSON(json, key, string) {
    for (var i = 0; i < json.length; i  ) {
        json[i][key] = json[i][key]   string;
    }
    return json1;
}


function add() {
    addStringToValueInJSON(blah, "test", "!");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
  <input type="text" id="test" name="test" value="2">
 
</form>

CodePudding user response:

Vanilla JS solution

const JSON = {}

const formData = new FormData(document.getElementById('myform'))
for (let [key, value] of formData.entries()) {
  key  = '_' // added as edit to answer at comment
  JSON[key] = `http://${value}`
}

console.log(JSON)
<form id="myform">
  <input type="text" id="test" name="test" value="2">
</form>

Multiples values version :

const JSON = {}

const formData = new FormData(document.getElementById('myform'))
for (let [key, value] of formData.entries()) {
  key  = '_' // added as edit to answer at comment
  const vals = value.split(',')
  
  const finalValsArray = vals.map(val => `http://${val}`)
  JSON[key] = finalValsArray.toString()
}

console.log(JSON)
<form id="myform">
  <input type="text" id="test" name="test" value="2,3,5">
</form>

  • Related