0

I am trying to create a JavaScript object to convert to a json to send via ajax

$("#submitList").on("click", function(){
    var Book = { book : new Array()};
    var sheetsArray = new Array();
    var preBook

     $(".add-list").each( function(){
        if($(this).is(":checked")){
            var BookName = $(this).val().split("+|+");
            var table = $(this).parents("tr").find("td:nth-child(2)").find('table');

            var objDetails = {
                    Name : $(table).attr("id"),
                    FirstRow : $(table).find(".FirstRow").is(":checked"),
                    emailcol : $(table).find(".emailcol option:selected").val()}

            if(preBook != BookName[0]){
                preBook = BookName[0];
                sheetsArray = new Array();  
                sheetsArray[BookName[1]] = objDetails ;
            }else{
                sheetsArray[BookName[1]] = objDetails ;
            }
            Book.book[BookName[0]] = sheetsArray;
        }
    });
    alert(JSON.stringify(Book));
    console.debug(JSON.stringify(Book));
})

but on the output of JSON.stringify(Book) all I get is

{"book":[]}

but the object looks like this

Object (
  [book] => Array(
    [Book3] => Array(
        [1-State.csv] => Object (
            [Name] => 1-State.csv
            [FirstRow] => true
            [emailcol] => 2
        )
        [2-country.csv] => Object (
            [Name] => 2-country.csv
            [FirstRow] => false
            [emailcol] => 2
        )
    )
    [Book1.2] => Array(
        [0-Sheet1.csv] => Object (
            [Name] => 0-Sheet1.csv
            [FirstRow] => true
            [emailcol] => 2
        )
    )
  )
)

I am not sure what the problem is, other then I think it maybe a problem with using array but from what I understand about stringify it should do both arrays and objects

jazzjazzy
  • 412
  • 3
  • 20
  • do `alert(JSON.stringify(Book));` just after `Book.book[BookName[0]] = sheetsArray;` – Mritunjay Jul 30 '14 at 04:09
  • You can find an explanation and solution in the duplicate. Just briefly here: `JSON.stringify` only considers numerical properties of an array, but you seem to be using non-numerical properties. – Felix Kling Jul 30 '14 at 04:10

1 Answers1

3

Looks like you are using Book.book as a key value pair, not as an array so defind book as an object instead of as an array

var Book = { book : {}};
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531