简体   繁体   中英

How to assign variable to json object

'I'm trying to assign a variable from a parent div to the json string of a child table and can't seem to get my javascript straight.

What I'd like to see, or some variation of:

{"blocks":[{"id":"115",courses:[{"Semester":"S,F","Credits":"3","Subject":"ACT"}‌​, {"Semester":"F","Credits":"6","Subject":"CSI"}]}] 

And the jQuery I have so far.

$('#update').click(function (e){
    var table = $('#table').tableToJSON();
    var blockId = $('#table').closest('div.Block').attr('id');
    table = {"block":table};
    document.getElementById('courseList').value = JSON.stringify(table);
}

I'm not sure how to add in the variable that I need in the object? How would I insert blockId?

I'm assuming bracket notation is what you're really looking for :

$('#update').on('click', function(){
    var table   = $('#table').tableToJSON();
    var blockId = $('#table').closest('div.Block').attr('id');
    var table2  = {};

    table2[blockId] = table;

    $('#courseList').val( JSON.stringify(table2) );
});

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