Question

I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.

At the last step I need to add that array to my object (myData) and then JSONify it.

Any ideas how I can do this, seems myData.push(filters); doesn't work...

Note that the object itself is not an array, I want to place an array IN the object.

       var myData = new Object();

        myData.deviceId = equipId;

        myData.dateTo = dateTo
        myData.dateFrom = dateFrom;
        myData.numResults = $("#numResults").val();
        var i=0;
        var filters = [];
        $('input[type=checkbox]').each(function () {
               if (this.checked) {
                   allData += $(this).val() + ",";
                    filters[i] = {
                        filterIds: $(this).val()
                    };
                    ++i;
               }
            });

        myData.push(filters);
Was it helpful?

Solution

That's not how to add items to an Object, change

myData.push(filters);

to

myData.filters = filters;

Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.

Read more about Array.prototype.push

OTHER TIPS

Use push to add elements to the filters array. Use property assignment to add another property to the myData object.

    var myData = {
        deviceId: equipId,
        dateTo: dateTo,
        dateFrom: dateFrom,
        numResults: $("#numResults").val()
    };
    var filters = [];
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            allData += $(this).val() + ",";
            filters.push({
                filterIds: $(this).val()
            });
        }
    });

    myData.filters = filters;

BTW, don't use new Object() to create an object, use {}.

Remove the need for an extra array and i.

var myData = {}

myData.deviceId = equipId;

myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
    if (this.checked) {
        allData += $(this).val() + ",";
        myData.filters.push({
            filterIds: $(this).val()
        });
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top