简体   繁体   中英

How do I store multiple tables of data in one Javascript object?

I'm using jQuery but I'm not sure if it's easier with just Javascript. The variables are going to be fairly large full of data (a few megabytes).

It's going to be:

table one -> {item one, item 2, item 3, item 4},
table two -> {item one, item 2, item 3, item 4},
table three -> {item one, item 2, item 3, item 4},
etc

I'm not sure what code is necessary to get it into this format though.

I'm basically reading from many html tables that have rows and columns of data in each table, and i want to combine everything into one variable to print at the end on the screen when I am done.

Using JSON you should have something like this:

data = { 
    table1:{
        row1: { data1: value, data2: value, ..., dataN: value },
        row2: { data1: value, data2: value, ..., dataN: value },
        ...
        rowN: { data1: value, data2: value, ..., dataN: value }
    },
    table2:{
        row1: { data1: value, data2: value, ..., dataN: value },
        row2: { data1: value, data2: value, ..., dataN: value },
        ...
        rowN: { data1: value, data2: value, ..., dataN: value }
    },
    ...
    tableN:{
        row1: { data1: value, data2: value, ..., dataN: value },
        row2: { data1: value, data2: value, ..., dataN: value },
        ...
        rowN: { data1: value, data2: value, ..., dataN: value }
    }
}

And, to access the second column, of the first row of the Nth table, you will have:

var value = data.tableN.row1.data2;

Do you absolutely have to store all the data in a variable? If not, you could print directly from your tables with something like this:

$('table').each(function() {
    $(this).each(function() {
        $(this).each(function() {
          console.log($(this).text());           
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM