Anand Deep Singh
Anand Deep Singh

Reputation: 2620

Create custom JSON object using jQuery

I want to create a custom multilevel JSON object. For that I have written some code, but it's not solving my purpose, although I am still working on it.

I need your suggestions to write the code.

There is a custom HTML table grid, where I want to save data when the user clicks on the save button.

Below should be the format to save data code in JSON.

table = {
    row0: {                         //this is row id
        td0: "some data",            // this is 1st row td data
        td1: "some data",
        td2: "some data",
        td3: "some data",
        td4: "some data",
        td5: "some data"
    },
    row1: {
        td0: "some data",            // this is 2nd row td data
        td1: "some data",
        td2: "some data",
        td3: "some data",
        td4: "some data",
        td5: "some data"
    },
}

I have created the below code, however it's not working as I mentioned above.

$("#myTable tbody tr").each(function () {
tdColId = $(this).attr("id");

$("#myTable tbody tr td").each(function () {
    tdId = $(this).attr("id"),
    tdContent = $(this).html();
    //console.log("this is row content "+tdcontent);        
})

item = {},
item["Column Id"] = tdColId,
item["Td Content"] = tdContent;


jsonObj.push(item);

});

Reference to full code is here.

Upvotes: 0

Views: 869

Answers (1)

limengjun
limengjun

Reputation: 183

you may try this:

jsonObj = {};
$("#myTable tbody tr").each(function() {
    tdColId = $(this).attr("id");
    jsonObj[tdColId] = {};

    $(this).find("td").each(function() {
        jsonObj[tdColId][$(this).attr("id")] = $(this).html();
    });

});

Upvotes: 2

Related Questions