JSBeginner
JSBeginner

Reputation: 41

Iterate jQuery elements in different order

Right now i am having a form called customers_form and looping through jquery in the sequence order and export the value as json output. I want to change in the order and change the name of the input element while converting to json like below

inputs = jQuery('#customers_form input')
    customerVal += "{" + "Customer"+ ":{";
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].id !== 'random_assignment_number') {
            customerVal += '"' + inputs[i].id + '"' + ':' + '"' + inputs[i].value + '"'+','
        } else {
            console.log(inputs[i].id)
        }
    }
 customerVal += "}}";

My Custsomers_Form order currently is

First_Name,
Last_Name,
DOB,
Addr1,
Add2,
City,
State,
Cntry,
Role

Expected output is like below in the order and need to change element id/name with the different name for json output from html element.

LAST NAME,
FIRST NAME,
ROLE,
STREET ADDRESS,
APT/BLVD,
CITY,
STATE,
COUNTRY,
DATE OF BIRTH

Upvotes: 0

Views: 21

Answers (1)

Barmar
Barmar

Reputation: 782107

Use an array that specifies the mapping between the input IDs and the keys you want in the JSON. And iterate through this array in order to get the properties in the order you want.

const input_mapping = [['LAST NAME', 'Last_Name'], ['FIRST NAME', 'First_Name'], ['ROLE', 'Role'], ...];
let customerObj = {Customer: {}};
input_mapping.forEach(([key, id]) => customerObj.Customer[key] = $("#" + id).val());
let customerval = JSON.stringify(customerObj);

Upvotes: 1

Related Questions