preface

Yesterday team members met a food in the business development for registration form after modifying food, how to send the modified data in the form of json to the backend problem, when I was in the solution to this problem, and found this problem quite interesting, so I send this question to the boiling point and group, saw everyone’s solution, learned a lot of knowledge.

This is the context for how to implement this feature, and any interested developers are welcome to read this article.

The problem background

As shown in the figure above, users can input the quantity of each dish in the menu registration table, and click save generated JSON data after input. The interface will put the supply date into the generated JSON data and send it to the back end, which will modify the data in the database after receiving the JSON data.

solution

Observation items after receiving the registration form, we found the name for the fixed data in the table, and other fields are the back-end return dynamic data, and the content of the form is dynamic, each row describes the names of the dishes as well as the number of items, we according to the known conditions to sort out the train of thought, the data with js extracted from the dom.

  • Gets the supply date and stores it in a variable.
  • Get the header data and store it in an array.
  • Gets the table contents and stores them in an array.
  • Iterate over the contents of the table, and store the data in the table in a JSON array corresponding to the table header.
  • Put a JSON array of dates and table contents into an object, and the callback interface sends the data to the back end.

The solution

After analyzing the page, we have a solution, which we can then translate into code:

  • DOM structure of dishes collection registration table is as follows:
<! -- Query list -->
<table class="search">
        <tbody><tr>
            <td>
Name: <input type="text" name="xm">&nbsp; Supply Date: <input type="text" id="gyrq" name="gyrq" onclick="wd.edit.datePicker({dateFmt:'yyyy-MM-dd'})" value="2020-04-30" id="gyrq">&nbsp;  <button type="button" class="btn" onclick="document.getElementById('form').submit();">The query</button>  </td>  <td style="text-align: right;">  <button type="button" class="btn" id="dc">export</button>  <button type="button" class="btn" id="dy">print</button>  </td>  </tr>  </tbody> </table>  <div class="list-div" id="tb1">  <table class="list">  <thead>  <tr>  <th style="text-align: center;">The name</th>   <th style="text-align: center;"> Beef 03 </th>   <th style="text-align: center;"> Chicken 002 </th>   </tr>  </thead>  <tbody wdoddclass="list-odd" wdevenclass="list-even" wdmouseoverclass="list-mouseover" id="wdTbody0">   <tr class=" list-odd">  <td style="text-align: center;"> Qingxiu hill </td>   <td style="text-align: center;">  <input type="text" style="width: 100px;" name="mc" value="0">  </td>   <td style="text-align: center;">  <input type="text" style="width: 100px;" name="mc" value="15">  </td>   </tr>   <tr class=" list-even">  <td style="text-align: center;">  a  </td>   <td style="text-align: center;">  <input type="text" style="width: 100px;" name="mc" value="0">  </td>   <td style="text-align: center;">  <input type="text" style="width: 100px;" name="mc" value="0">  </td>   </tr>   </tbody>  </table> </div> Copy the code
  • Write JS code according to DOM structure to get the data we need
// Table object
let tableObj = {};
// Supply date
tableObj.gyrq = $("#gyrq").val();
// Get all the titles
const titleArr = $("#tb1 table thead tr"); // Get all the content const contentArr = $("#tb1 table tbody");  // List data let data = []; // Iterate over everything for(let i = 0; i < contentArr.children().length; i++){  // Each content object  let obj = {};  // Walk through all the headings  for(let j = 0; j < titleArr.children().length; j++){  // Get each title  let key = (titleArr.children().eq(j).html()).replace(/\s/g."");  if(j ===0) { // The dom structure of the name is HTML  obj[`${key}`] = (contentArr.children().eq(i).children().eq(j).html()).replace(/\s/g."");  }else{  // The dom structure of the other fields is input  obj[`${key}`] = (contentArr.children().eq(i).children().eq(j).children().val()).replace(/\s/g."");  }  }  // Put each object into an array  data.push(obj); } tableObj.data = data; Copy the code
  • The interface is called to send the obtained JSON data to the background
$.ajax({
   url:"".   data:tableObj,
   type:"POST".   success:(res) = >{
  } }) Copy the code

JSON secondary processing

After the above code converted the data in DOM into JSON, the back end said that this was not the format he wanted, he could not parse the data, and then sent me the JSON format, asking me to transfer it according to his format.

I said to the back end: you directly on your side of the format you want to be good. Back end: you directly in the page turn, I back end turn words will cause unnecessary waste of resources. Me: All right, I’ll turn.

  • Json format from the back end:
{
  time:"xxxx-xx-xx".  data: [    {
        name:"xx". title:"". num:""  }  ] } Copy the code
  • I parse the JSON format
{
  "time":"2020-04-30".  "data": [    {"Name": "Green And Beautiful Mountain".03 "beef": "0"."Chicken 002": "15"},
    {"Name": "a".03 "beef": "0"."Chicken 002": "0"}
 ] }  Copy the code

The difficulties in analysis

The data needed on the back end is to split each person’s data.

For example, the customer named Qingxiushan ordered beef 03 with a quantity of 0 and chicken 002 with a quantity of 15.

Customer A, he ordered beef 03 with 0 quantity and chicken 002 with 0 quantity.

After converting to JSON, the code looks like this:

{
  "time": "2020-04-30".  "data": [
    {
      "name": "Green And Beautiful Mountain". "title": 03 "beef". "num": "0"  },  {  "name": "Green And Beautiful Mountain". "title": "Chicken 002". "num": "15"  },  {  "name": "a". "title": 03 "beef". "num": "0"  },  {  "name": "a". "title": "Chicken 002". "num": "0"  }  ] } Copy the code

After looking at the JSON data we generated and the json data we needed at the back end, we found the following patterns:

  • In the JSON data we generate, the name is a known field and the other fields are dynamically unknown.
  • The number of JSON objects in the DATA required by the back-end is determined by the number of dynamic fields in the JSON data we generate.

Code implementation

Now that we know the pattern, we can implement the parser in JS.

/ * ** JSON parser * @param jsonObj
 * @returns {{}}
 * @constructor * / const JsonParse = function (jsonObj= {}) {  let resultObj = {};  // Time is a fixed value, so can be directly retrieved  resultObj.time = jsonObj.time;  resultObj.data = [];  for (let i = 0; i < jsonObj.data.length; i++){  // Get each item in the array  const dataObj = jsonObj.data[i];  // Convert each item into a JSON object  let resultDataObj = {};  // The converted object name. Since the name is a fixed value, it needs to be added when traversing the object.  let resultDataObjName = "";  // Iterate over each item in the array  for (let key in dataObj){  // Terminate the loop if the key in dataObj does not exist  if(! dataObj.hasOwnProperty(key))continue;  // Name is a fixed condition  if(key === "Name") { // Record the name  resultDataObjName = dataObj["Name"];  }else{  // Dynamic condition, in which key is a value other than the name, gets the name and quantity of the current key  resultDataObj.name = resultDataObjName;  resultDataObj.title = key;  resultDataObj.num = dataObj[key];  // Name, title, num are known values, put the current object into the result object's data  resultObj.data.push(resultDataObj);  // Empties the current object and continues traversal for the next key  resultDataObj = {};  }  }  }  return resultObj; } Copy the code

Run tests on the above code

// Test data
const dataObj ={
    "time":"2020-04-30".    "data": [        {"Name": "Green And Beautiful Mountain"."Beef": "0"."Chicken": "15"},
 {"Name": "a"."Beef": "0"."Chicken": "0"."Eggs":"12"},  {"Name": "test"."Pork": "0"."Duck": "0"}  ] }  console.log(JsonParse(dataObj)); Copy the code

The realization idea of net friend

It is an interesting problem to convert our generated JSON to the format required by the back end. So I posted the problem to the group and the gold boiling point to see how everyone thought to solve the problem, and then I posted your implementation code.

  • Boiling point comment section user: @boboka123’s solution
  • Alumnus @_Dreams’ solution
  • Group friend @Cavey’s solution
  • Qunfriend@SSH solution
  • Group friends @ listen to the waves in your heart, solutions

Write in the last

  • If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
  • This article was first published in nuggets. Reprint is prohibited without permission 💌