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

105
Views
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 answers
Answer question

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 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!