在JavaScript中将列表推入数组

euoag5mw  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(107)

我有一个从动态输入中获得的数据列表

FirstNames : Person1 FN, Person2 FN, Person3 FN, ...
   LastNames : Person1 LN, Person2 LN, Person3 LN, ...

该列表是动态的,我通过输入名称来获取值,如下所示

var FirstNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();

我想把这些和许多其他的作为一个数组传递到我的C#后端,如下所示

details:[
   0: {FirstName: 'Person1 FN', LastName: 'Person1 LN'}
   1: {FirstName: 'Person2 FN', LastName: 'Person2 LN'}
   ....................................................
   N{FirstName: 'PersonN FN', LastName: 'PersonN LN'}
  ]

我尝试了许多不同的方法,如split()Push(),如下所示

let FNs = [];
  let FN = FirstNames.toString().split(',');
  console.log("Splitted First Names : "+TFNs);

  $.each(TFNs, function(){
      FNs.push({FirstName:$(this)}.toString());
  });
  console.log("First Names[] : "+FNs);

编辑:* 添加了表单标记(动态)& JS Save()函数 *

以下是表单(动态生成)

function GenerateFrms(Id) {
         //alert('Function Scripts');
        $("#FrmContainer").empty();
        var html = "";


        $.ajax({
            type: "POST",
            url: "WebService.asmx/GenerateForms",
            data: "{'Id':'" + Id + "'}",
           
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                console.log(Object.values(data))
                try {
                    for (var i = 0; i <= data.d.length; i++) {
                   
                        if (data.d[i].Persons != "0") {
                            
                            html += " <div class='theme-box-shadow theme-border-radius bg-light mb-3'> ";

                            html += "   <div class='row border-bottom py-2 m-auto'> ";
                            html += "  <div class='col-8'>";
                            html += "   <div class='fw-bold font-medium'> Details </div> ";
                            html += "   </div> ";

                            html += "<div class='col-4 text-end align-self-center'> ";
                            html += " <a class='font-small' data-bs-toggle='collapse' href='#collapseFrm' role='button' aria-expanded='false' aria-controls='collapseFrm'><i class='bi bi-chevron-down ps-1'></i></a>";
                            html += " </div>";
                            html += " </div>";

                            html += "  <div class='' id='collapseFrm'> ";

                            html += " <div class='row'> ";
                            html += " <div class='col-sm-12'> ";
                            html += " <div class='px-3 FrmDetails' id='FrmDetails'> ";

                            for(var j=1; j<=data.d[i].Persons; j++)
                            {

                                html += " <legend class='fw-bold' style='border-bottom:2px solid blue;'> Persons " + j + " Details</legend> ";
                                html += " <ul class='row py-3'> ";

                                html += " <li class='col-12 col-md-12 pb-3'> ";

                                html += " <div class='row'> ";
                                html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
                                html += " <label for='inlineFormSelectTitle3'>  selected Title </label> ";
                                html += " <select class='form-select Title' name='Title' id='Title" + j + "' > ";
                                html += " <option selected>Title</option> ";
                                html += " <option value='Mr'>Mr.</option> ";
                                html += " <option value='Mrs'>Mrs.</option> ";
                                html += " <option value='Ms'>Ms.</option> ";
                                html += " </select> ";
                                html += " </div> ";

                                html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
                                html += " <label for='inlineFormSelectTitle3'>  First Name </label> ";
                                html += " <input type='text' class='form-control  FirstName' name='FirstName' id=' FirstName" + j + "' placeholder='First Name'> ";
                                html += " </div> ";

                                html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
                                html += " <label for='inlineFormSelectTitle3'> Last Name </label> ";
                                html += " <input type='text' class='form-control  LastName' name='LastName' id=' LastName" + j + "' placeholder=' Last Name'> ";
                                html += " </div> ";

                                html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
                                html += " <label for='inlineFormSelectTitle3'> Date of Birth </label> ";
                                html += " <label class='visually-hidden' for='DateofBirth'> Date of Birth</label> ";
                                html += " <input type='date' class='form-control DOB' name='DOB' id='DOB" + j + "'> ";
                                html += " </div> ";
                                html += " </div> ";
                                html += " </li> ";

                                
                                html += " </li> ";
                                html += " </ul> ";
                            }
                           

                            html += " </div> ";
                            html += " </div> ";
                            html += " </div> ";
                            html += " </div> ";
                            html += " </div> ";
                        }
                        $("#FrmContainer").append(html)
                    }
                    //

                    
                } catch (e) {
                    console.log(e);
                }
            },
            error: function (xhr, status, e) { alert(xhr.responseText); }
        });

    }

脚本函数与样本静态数据我现在工作(我想得到他们从上述形式动态)

function Save() {
        $('#create').prop('disabled', true);
        
        //Reading Values from the respective inputs/select
        var Titles = $("select[name='Title']").map(function(){return "Title:"+$(this).val();}).get();
        var FNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
        var LNames = $("input[name='LastName']").map(function(){return $(this).val();}).get();
        var DOBs = $("input[name='DOB']").map(function(){return "DOB:"+$(this).val();}).get();

        //here I want to put them in array like `details[]` array below
        setTimeout(function () {

            let details=[];
            
            details.push({
                Title:"Mr.",
                FirstName:"Person1 FN",
                LastName:"Person1 LN",
                DOB:"1990-05-20"
            });
            
            details.push({
                Title:"Mrs.",
                FirstName:"Person2 FN",
                LastName:"Person2 LN",
                DOB:"2001-06-18"
            })
             console.log(details);

            var DataCarrier = {
                Id: Id, //From Query string
                 PersonsDetails:details
                };

               $.ajax({
                type: "POST",
                url: "WebService.asmx/SavePersons",
                data: JSON.stringify(DataCarrier),
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    try {
                        if (data != null) {
                            setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 500);
                        }
                       
                    } catch (e) {
                        console.log(e);
                    }
                },
                error: function (xhr, status, e) { alert(xhr.responseText); }
            });

            }, 5000);
        }

还有那个按钮

<input id="btnSave" class="btn btn-effect btn-book px-5" type="button" value="Continue" onclick="Save();" />

但我得到他们作为

[object Object],[object Object],[object Object],[object Object],[object Object]

我还尝试了.toString(),但没有任何变化,console.log("FNs : "+json.stringify(FNs));抛出错误。
我如何处理这些数据,如上面提到的,然后再把它们传递到后端?我做错了什么?有没有一个更好的方法来做我想实现的?

nzkunb0c

nzkunb0c1#

我认为数组中firstName和lastName的索引是相同的

var FirstNames = $("input[name='FirstName']")
.map(function(){return $(this).val();}).get();
var LastNames = $("input[name='LastName']")
.map(function(){return $(this).val();}).get();

var FN = FirstNames.map((FN,index) => {
   return {{FirstName: FN, LastName: LastNames[index]}
})

应该是你想要的那种

相关问题