B. Clay Shannon B. Clay Shannon - 6 months ago 11
Javascript Question

What syntax do I need to use to add a temporary array to a member of an object that equates to a generic list of string?

Based on the answer here, I thought I could declare and assign to an array this way:

var _recipients = [];
if ($('#email1').length > 0) {
_recipients.push($('#email1').val());
}
if ($('#email2').length > 0) {
_recipients.push($('#email3').val());
}
if ($('#email3').length > 0) {
_recipients.push($('#email3').val());
}


...and then trying to add that array to a member of an object like so:

var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').is(':checked'),
scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').is(':checked'),
scheduleFillRate: $('#ckbx_fillratebycustomer_location').is('checked'),
schedulePriceCompliance: $('#ckbx_pricecompliance').is('checked'),
recipients.push(_recipients),
. . .


...but JSLint complains about that last line of code, saying, "Expected ':' and instead saw '.'."

In more context, this last is part of an AJAX call:

var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').is(':checked'),
scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').is(':checked'),
scheduleFillRate: $('#ckbx_fillratebycustomer_location').is('checked'),
schedulePriceCompliance: $('#ckbx_pricecompliance').is('checked'),
recipients.push(_recipients),
generationDayOfMonth: $('#dayofmonthselect').val(),
generationOrdinal: $('#ordinalselect').val(),
generationDayOfWeek: $('#dayofweekselect').val(),
generationWeekOrMonth: $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: $('#delperffrom').val(),
daterangeToDeliveryPerformance: $('#delperfto').val(),
daterangeFromFillRate: $('#fillratefrom').val(),
daterangeToFillRate: $('#fillrateto').val(),
daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
daterangeToPriceCompliance: $('#pricecomplianceto').val()
};

$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});


...which was working fine when I was just adding one value to "recipients" like so:

recipients: $('#email1').val(),


In the Model on the server, recipients is a generic list of string:

public class UnitConfigVals
{
. . .
public List<string> recipients { get; set; }
. . .


What do I need to fix for this array-assigning to work?

Answer

Change

recipients.push(_recipients),

to

recipients: _recipients

your currently calling a function instead of making an assignment.

Side note: you can replace your first code block with

var _recipients = $('[id^="email"]').map(function () {
    return $(this).val();
}).get().filter(function (y) {
    return y != '';
});