This is the first day of my participation in the More text Challenge. For details, see more text Challenge

In my recent project, there was a need to save after editing the list page. Because of the large amount of data saved, only the modified data was sent to the back end. Since the page is too complex to listen to through the watch (the key is to compare), I use a for loop to do this.

First, the data format looks like this:

Const savedData = [{" pinci ":" 1 day 1 ", "name" : "zxhtest", "id", 5524, "zhuangtai" : "2"}, {" pinci ":" 1 day 1 ", "Name" : "zxhtest", "id", 5530, "zhuangtai" : "1"}, {" pinci ":" 1 day 1 ", "name" : "zxhtest", "id", 5536, "zhuangtai" : ""}, {" pinci ":" on January 1 ", "name" : "zxhtest", "id", 5542, "zhuangtai" : "1"}, {" pinci ":" 1 day 1 ", "name" : "zxhtest", "id" : 5545, "zhuangtai":"1" }, ]; Const newAddData = [{"pinci":"1 ", "name":" action item test ", "id":5507, "zhuangtai":"1", "delete": True,}, {" pinci ":" 1 day 1 ", "name" : "zxhtest", "id", 5517, "zhuangtai" : "2"}, {" pinci ":" on January 1 ", "name" : "ZXH test plan template", "Id" : 5562, "zhuangtai" : "1"}, {" pinci ":" 1 quarter 1 times ", "name" : "ZXH test plan template", "id", 5568, "zhuangtai" : ""}]Copy the code

Description of variables: savedData: savedData; NewAddData: new data;

The parameters are described as follows: Name: unique. Id: Data that has been saved has a unique ID, but new data does not. Delete: delete this data; Pinci and zhuangtai: These two fields may be repeated; Except for id, all parameters (name, pinci, zhuangtai) are changeable

If there is no id in the object, the new data will be inserted into the result. Then judge that if name, pinci and zhuangtai are not equal, it means that the data has been modified and put into result. Delete = true; delete = true; delete = true; delete = true; This extracts the changed data.

const result = []; for (let i = 0; i < newAddData.length; i++) { const current = newAddData[i]; const equalObj = savedData.find(item => item.id === current.id); if (! equalObj) { result.push(current); } else if (current.name ! == equalObj.name || current.pinci ! == equalObj.pinci || ++current.zhuangtai ! == ++equalObj.zhuangtai) { result.push(current); } if (current.smZHDelete) { result.push(current) } }Copy the code

PS: In fact, this problem has been bothering me for a long time, I tried many methods, such as using double loop, using fileter, but I could not achieve it well. Finally, I asked the big guy, and it came out in less than 2 minutes. After looking at the code, I: Huh? Is this it? Ok, I sure as expected or vegetables.