문제

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);
도움이 되었습니까?

해결책

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

다른 팁

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()
        });
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top