简体   繁体   中英

Convert Array object into string jquery

I am posting a form via ajax and want to send the form data like string . Below is my code .

var formdata=$(this).serializeArray();
var objList = [];
for (var i = 1; i <= $("input[name=Range]").val(); i++) {

tempObj = {};

$.each(formData, function (key, value) {


                        if (value.name.startsWith("member"){

                        }
                        else {
                            tempObj[value.name] = value.value;
                        }

                    });


                    tempObj["member"] = $("input[name=member"+i+"]").val();

                    tempObj["Range"] = 1;




                    objList.push(tempObj);

                }

                console.log(objList);

If Range = '2' I get 2 Array Object in console like this:

Name:"John"  
Department:"Training"  
Areacode:"23"
Member:"2"



Name:"Sam" 
Department:"HR"
Member:"2"
Areacode:"13"

But I want to post is data as a Form Url like:

"Name=John&Department=Training&Member=2&Areacode=23"   



  "Name=Sam&Department=HR&Member=1&Areacode=13" 

What can I do in code ?

I will continue your code insteed of modifying what you have.

We start from objList . And we will map this array to create a new array but insteed of an object array it will be a string array.

You can then add the reduce method to iterate over the object and crete you string no matter how many values it has.

 var formdata = $(this).serializeArray(); var objList = [{ Name:"John", Department:"Training" , Areacode:"23", Member:"2"},{ Name:"Sam" , Department:"HR", Member:"2", Areacode:"13", Extra:"value"}]; let arrStr = objList.map(obj => { return Object.entries(obj).reduce( (key, val,i) => `${key}${i>0?'&':''}${val[0]}=${val[1]}`, ""); }) console.log("This is the array of strings:"+arrStr); console.log("String 1:"+arrStr[0]); console.log("String 2:"+arrStr[1]); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> "Name=John&Department=Training&Member=2&Areacode=23" 

Hope this helps :)

From the tempObj you already have:

 const tempObj = { Name:"John" , Department:"Training" , Areacode:"23", Member:"2" } const strObj=Object.entries(tempObj).reduce( (str, entry,i) => `${str}${i>0?'&':''}${entry[0]}=${entry[1]}`, "") console.log(strObj) 

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