1

Suppose I have HTML like this,

<table id="Words">
<tr>
    <td class="cell">Hello</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Bye</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Tricicle</td>
    <td class="desc">A toy</td>
</tr>

Is there any elegant way/function to convert this to Javascript associative array? How to go about it?

1
  • 1
    <pedant>Javascript doesn't have associative arrays only objects and numeric arrays (objects with numeric keys)</pedant> Commented Apr 13, 2012 at 7:47

5 Answers 5

4
$('tr').map(function(){
    return {
        cell: $('.cell', this).text(),
        desc: $('.desc', this).text()
    }
})

jQuery(Object { cell="Hello", desc="A word"}, Object { cell="Bye", desc="A word"}, Object { cell="Tricicle", desc="A toy"})
Sign up to request clarification or add additional context in comments.

Comments

1

http://jsfiddle.net/cyFW5/ - here and it will works for every td with a class

$(function() {

    var arr = [],
        tmp;

    $('#Words tr').each(function() {

        tmp = {};

        $(this).children().each(function() {

            if ($(this).attr('class')) {
                tmp[$(this).attr('class')] = $(this).text();
            }

        });

        arr.push(tmp);
    });

    console.log(arr);

});​

Comments

1
var table = [];
$('table tr').each(function() {
    var row = [];
    $(this).find('td').each(function() {
        var cell = {};
        cell[$(this).attr('class')] = $(this).html();
        row.push(cell);
    });
    table.push(row);
});

Comments

0

Here's a demo, watch the console.

$(function() {

    var words = [];

    $('#Words tr').each(function() {
        words.push({
            cell: $('.cell', this).text(),
            desc: $('.desc', this).text()
        });
    });

    console.log(words);

});​

Comments

0

Given this specific use case then this would work:

var results = {};
$('table#Words tr').each(function(i, x){
    results[i] = {
      desc: $(x).find('.desc').text(),
      cell: $(x).find('.cell').text()
    }
});

But why have the whole conversion to an object? What's it being used for, there might be an easier method of walking through the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.