2

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:

  • If I've seen the key before, add a new key
  • If I have seen the key before, continue building the string

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:

  • Instead of adding an entry to the object at key isbn13, it adds object.isbn = ...
  • 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)

2
  • 2
    Don't use newRowStr = '<tr>' and so on. There is a createElement() method for creating nodes and appendChild() for appending them to DOM Commented Nov 5, 2013 at 14:13
  • Thnx! Good tip I will use @GlenSwift Commented Nov 5, 2013 at 14:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.