Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda