Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Add element for each value of the key - JSON

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!