Reputation: 9966
Okay, I have the following scenario: I get an object, which is an array with lists. There is always 3 items in the array.
The items inside the lists, has a specific field I am interested in (ISBN13).
I want to build a table like this using JavaScript:
<table>
<tr>
<td>Array_1_Item_1_ISBN13</td>
<td>Array_2_Item_1_ISBN13</td>
<td>Array_3_Item_1_ISBN13</td>
</tr>
<tr>
<td>Array_1_Item_2_ISBN13</td>
<td>Array_2_Item_2_ISBN13</td>
<td>Array_3_Item_2_ISBN13</td>
</tr>
</table>
In C#, I would just build a dictionary, and:
But now I am in jQuery/JS land, and meh.
Below, I have tried to create an object, I use to fill data in. This code have the following issues:
Not sure if the if() statement works
function setBookTableFromProducts(data) {
var outputArray = {};
// list is an array of books, e-books and audiobooks)
$.each($.parseJSON(data), function (index, value) {
// single type of book
$.each(value, function (index_inner, book) {
var isbn13 = book.ISBN13;
if (outputArray.isbn13 == null) {
var newRowStr = '<tr>';
newRowStr += '<td>' + book.ISBN13 + '</td>';
outputArray.isbn13 = newRowStr;
} else {
outputArray.isbn13 += '<td>' +book.ISBN13+ '</td>';
}
});
});
$.each(outputArray, function (index, trArr) {
trArr += '</tr>';
$('#bookTable').append(trArr);
});
}
How would you solve this issue? What is wrong with my code? (Oh, and performance doesn't matter)
Upvotes: 2
Views: 136
Reputation: 2150
It would help if you provided an example of the input (i.e. $.parseJSON(data)) or maybe created a jsFiddle.
But one possible issue is outputArray.isbn13
. You have var isbn13 = book.ISBN13
take some ISBN value (say 9783161484100) then expect to use it as a key to the outputArray
object with outputArray.isbn13
. However, the key is isbn13
and not outputArray.9783161484100
. Instead, try
var isbn13 = book.ISBN13;
if (outputArray[isbn13] == null) {
...
}
This will then get interpreted as outputArray.9783161484100
.
Upvotes: 2