简体   繁体   中英

Push a list into array in JavaScript

I have a list of Data I get from dynamic inputs like this ones

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

The list is dynamic and I'm Getting the values by input Name like this

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

I want to pass these and many others to my C# backend as an array like This

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

I tried many different approaches like split() & Push() as below

  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);

Edit : Added Form markup(dynamic) & JS Save() Function

Here is the form (dynamically generated)

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); }
        });

    }

The Script function with Sample static data I'm working with now(I want get them dynamically from the above form)

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);
        }

And the button

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

But I'm getting them as

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

I also tried .toString() but nothing changes, And console.log("FNs: "+json.stringify(FNs)); is throwing error.

How can I process these data as mentioned above before passing them to the backend? What I'm doing wrong? Is there a better way to do what I want achieve?

I think the index of firstName and lastName in your array is identical so

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]}
})

It should be something like what you want

First step is to read the values from the inputs or select

  //Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function() { return $(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 DOB = $("input[name='DOB']").map(function() { return $(this).val(); }).get();

Then split the values into array

 //splitting the values into arrays
let TL = Titles.toString().split(',');

let FN = FNames.toString().split(',');

let LN = LNames.toString().split(',');

let BD = DOB.toString().split(',');

After that you can push them into the details[] array using for loop like this

let details = [];

for (var i = 0; i < FNames.length; i++) {
    details.push({
        Title: TL[i],
        FirstName: FN[i],
        LastName: LN[i],
        DOB: BD[i],
        TravllerType: TT[i]
    });
}
console.log(JSON.stringify(details));

Note: if you console.log(details); you will find out that its object:Object stuff, to get around this, we stringify it.

finally incorprate all that into your SavePersons() function

function SavePersons() {

        $('#create').prop('disabled', true);

        //Reading Values from the respective inputs/select
        var Titles = $("select[name='Title']").map(function () { return $(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 TravllerTypes = $("input[name='TravllerType']").map(function () { return $(this).val(); }).get();
        var DOB = $("input[name='DOB']").map(function () { return $(this).val(); }).get();


        //splitting the values into arrays
        let TL = Titles.toString().split(',');

        let FN = FNames.toString().split(',');

        let LN = LNames.toString().split(',');

        let TT = TravllerTypes.toString().split(',');

        let BD = DOB.toString().split(',');


        setTimeout(function () {

            let details = [];

            for (var i = 0; i < FNames.length; i++) {
                details.push({
                    Title: TL[i],
                    FirstName: FN[i],
                    LastName: LN[i],
                    DOB: BD[i],
                    TravllerType: TT[i]
                });
            }
            console.log(details);

            var DataCarrier = {
                Id: Id,
                TravelersDetailsTT: 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; }, 5000);
                    }
                   
                } catch (e) {
                    console.log(e);
                }
            },
            error: function (xhr, status, e) { alert(xhr.responseText); }
        });

        }, 5000);
    }

it may not be the best answer but it works and I tested it. any improves are welcome. in the mean time I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM