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

106
Visualizações
Dynamic JSON creation using jQuery

I am new to JSON and tried the below example to see the results but it returns an empty array in the console. Any suggestions?

function createJSON() {
  var obj = [];
  var elems = $("input[class=email]");
  
  for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
      'title': id,
      'email': email
    };
    obj.push(tmp);
  }
  
  var jsonString = JSON.stringify(obj);
  console.log(jsonString);
}

createJSON();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The issue with your code is because you're mixing plain JS and jQuery methods. For example, you shouldn't iterate through a jQuery object with a for loop, and a jQuery object doesn't have a getAttribute() method. You would use each() and attr() or prop() in those cases, respectively.

That said, you can more simply create an array from a jQuery object containing a collection of elements using map(), something like this:

function createJSON() {
  let arr = $('.email').map((i, el) => ({
    title: el.title,
    email: el.value
  })).get();
  return JSON.stringify(arr);
}

let json = createJSON();
console.log(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<input type="email" class="email" title="email_1" value="foo@foo.com" />
<input type="email" class="email" title="email_2" value="bar@bar.com" />

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