1

I'm actually using this method, but it only returns me an array of arrays of values, I need a way to set a key and value, setting each key to <td> name property would be fine.
If you have any solution in mind, please share.

HTML:

<table id="mytable">
<tr>
    <td name="name">Juan</td>
    <td name="age">23</td>
    <td name="random">1990</td>
</tr>
<tr>
    <td name="name">Jonhatan</td>
    <td name="age">25</td>
    <td name="random">1980</td>
</tr>
<tr>
    <td name="name">Pete</td>
    <td name="age">20</td>
    <td name="random">1991</td>
</tr>

Javascript:

$(document).ready(function(){
    $('#output').html('OUTPUT: '+tableToJson('#mytable'));
});

function tableToJson(table){
    var AoA = $(table+' tr').map(function(){
        return [
            $('td',this).map(function(){
                return $(this).text();
            }).get()
        ];
    }).get();
    return JSON.stringify(AoA);
}

Current output:

[["Juan","23","1990"],["Jonhatan","25","1980"],["Pete","20","1991"]]


Output needed:

[
[{'name':"Juan"},{'age':"23"},{'random':"1990"}],
[{'name':"Jonhatan",{'age':"25"},{'random':"1980"}],
[{'name':"Pete"},{'age':"20"},{'random':"1991"}]
]



JsFiddle:
http://jsfiddle.net/j4x7pr2w/1/

1

2 Answers 2

1
function tableToJson(table){
    var AoA = $(table).find('tr').map(function(){
        var result = {};
        $('td',this).each(function(){
            var $this = $(this);
            result[$this.attr('name')] = $this.text();
        });
        return result;
    }).get();
    return JSON.stringify(AoA);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You probably mean $(table).find("tr") (that way you can pass an element or more complex selector as the argument).
@soktinpk: Yes, true. I changed the code minimally from OP's, and didn't look closer at the surroundings. But you are correct, and it makes sense to change it.
1

DEMO

The following code should fix it. It's basically an outer .each() with an inner .map().

$(function() {
    var AoA = [];
    $('#mytable').find('tr').each(function(i,tr) {
        var BoB = $(tr).find('td').map(function(j,td) {
            var thisTD = {};
            thisTD[ $(td).attr('name') ] = $(td).html();
            return thisTD;
        }).get();
        AoA.push( BoB );        
    });
    $('body').append( JSON.stringify( AoA ) );
});

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.