Analyzing the code showed by this SO question, I just noticed the way it's using jQuery to iterate a JSON array:
$(data).each(function() {
while in my mind an array should rather be iterated this way:
$.each(data, function() {
Indeed, the jQuery.each() manual page states:
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.
But since the OP seemed to have his code at least partially working I was curious to test, and discovered that it works!
Here is the proof:
var data = [
{"key": "value-1"},
{"key": "value-2"},
{"key": "value-3"}
];
$(data).each(function() {
document.write('<br />' + this.key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So if $(data).each()
works when data
is a JSON array, it seems to mean that this array is an acceptable content for $(data)
to return a jQuery object.
Then pursuing the investigation I checked the jQuery(elementArray) manual page and looked at the jQuery( elementArray )
section, which states:
elementArray
Type: Array
An array containing a set of DOM elements to wrap in a jQuery object.
According with the above, an array of objects (instead of DOM elements) should fail.
So I tested to compare the objects returned by either this $(data)
and a simple $('body')
. Here is the result:
var data = [
{"key": "value-1"},
{"key": "value-2"},
{"key": "value-3"}
];
function log(obj, init) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var $row = $('tr[data-prop=' + prop + ']');
if (!$row.length) {
$row =
$('<tr data-prop="' + prop + '"><th>' + prop + '</th></tr>')
.appendTo($('table'));
if (!init) {
$row.append('<td></td>');
}
}
$row.append('<td>' + JSON.stringify(obj[prop]).substr(0,25) + '</td>');
}
}
}
log($('body'), true);
log($(data), false);
table {
border-collapse: collapse;
border: 1px solid #000;
}
th, td {
border: 1px solid #000;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Property</th>
<th>$('body')</th>
<th>$(data)</th>
</tr>
</table>
Actually it appears that everything can be converted to a jQuery object.
I'm puzzled: am I reinventing the wheel!?