When I was working on a question option function, I encountered this merge problem. There are single-choice and multiple-choice questions. Single-choice is no problem. Each question has one answer. Multiple-choice will result in multiple answers. The selection result is similar to the picture below:
I need to merge the data of the same multiple-choice question into one, that is, the objects in the blue box selection part in the picture are merged into one, the option becomes "pinch, squeeze", and other IDs are ignored. Is there any simple way to achieve this. Kneel down and thank you!
A basic idea is to traverse the data first, save the questions of the same question as an array, then traverse the arrays dealing with the same question, and splice the answers.
Example:
Data:
//Category the same questions
Traverse questions of the same type, and put all the following questions into the first one.
and re-store it in the original format
Update
After reading the answer on the 2nd floor, in fact, the previous process can be simplified, but as the 3rd floor said, it has nothing to do with the ES6 map. I used ES5
forEach
. Instead of using ES5, just use ES3. There is no problem at all if you replace it with a normal for loop. Using map is quite complicated.Since there is no need to classify the question data, the answers can be spliced directly without classifying them first. The implementation is as follows:
What comes out like this
data2
is in the form of an object. If you need an array, just process it.I still have to agree with the point on the third floor. Even if it is a multiple-choice question, the original data should not be organized in the way you listed. Isn’t it a better way to handle it directly when counting the selected answers to multiple-choice questions?
Provides a fun idea that can be implemented, but may not be applicable to real scenarios;
Define an empty object, loop through the array, and then the attribute of the empty object is named title and the corresponding value is the title; the value is an array, and the option Push it in. Of course, this may also involve the issue of duplication removal in each question. The final result is probably similar to this
If you can use es6, I recommend Map
The method on the 1st floor can solve this problem.
The map on the 2nd floor does not need to be es6.
The 3rd floor refused to answer this question because he felt that this implementation method was not right