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>
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" />