Search code examples
javascriptarraysjsonstringify

Attempting to use JSON to stringify an object that holds an array of objects


When trying to stringify an object that holds an array of objects, I'm getting an empty array when I can see I have values.

 filterDto: {
            Expressions: []   
        },

/* Using a tempArray to see if its an object issue of my filterDto.Expressions */

fnBuildFilterValues: function() {

            var invoiceObj = this;

             var tempArray = new Array();


              $("#tblExpressions tr").each(function() {

                var doWeAddRow = false;
                var filterObject = {
                    "Field": {},
                    "Condition": {},
                    "DataValue": {}
                };

                $(this).find(":input").each(function() {

                    if (  $(this).attr('name') === 'ddlFieldExp' ) {
                        filterObject.Field =  $(this).val();
                    }
                    if (  $(this).attr('name') === 'ddlConditionExp' ) {
                        filterObject.Condition =  $(this).val();
                    }
                     if (  $(this).attr('name') === 'tbDataExp' ) {
                        filterObject.DataValue =  $(this).val();
                    }

                }); /* Inner loop */

              tempArray.push(filterObject); 

              }); /* Outer loop */

              invoiceObj.filterDto.Expressions = tempArray;
        },

And what I want is to use something like:

     var objToString = {};
     objToString = JSON.stringify(invoiceObj.filterDto)

I've tried using = {} as a remedy but I still end up with ObjToString being empty when my array is populated. It's show as this: {"Expressions":[]}

If I do a quickwatch in VS on the right hand portion, the JSON.Stringify I get this:

    JSON.stringify(invoiceObj.filterDto) 
    "{"Expressions":[{"Field":"6","Condition":"0","DataValue":"2"}]}"   String

But why is the ObjToString showing an empty result?


Solution

  • The code you've pasted is working fine as evidenced by this code (JSON serialization in console.log).

    Is your issue that fnBuildFilterValues is not called before the serialization attempt? Is your issue that any of your selectors aren't yielding any results? The problem does not appear to be with the pasted code.