Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda