蝴蝶刀刀
一个基本思路,先把数据遍历一遍,相同问题的题目存为一个数组,然后遍历处理相同题目的数组,将答案拼接即可。示例:数据:var questions = [{ id: Math.random() * 100000 >> 0, option: 'x', questionId: 1, title: '你的名字'}, { id: Math.random() * 100000 >> 0, option: '动作1', questionId: 2, title: '你喜欢的动作'}, { id: Math.random() * 100000 >> 0, option: '动作2', questionId: 2, title: '你喜欢的动作'}, { id: Math.random() * 100000 >> 0, option: '动作3', questionId: 2, title: '你喜欢的动作'}, { id: Math.random() * 100000 >> 0, option: '动作4', questionId: 2, title: '你喜欢的动作'}, { id: Math.random() * 100000 >> 0, option: '动作5', questionId: 2, title: '你喜欢的动作'}, { id: Math.random() * 100000 >> 0, option: '歌曲1', questionId: 3, title: '你喜欢的歌曲'}, { id: Math.random() * 100000 >> 0, option: '歌曲2', questionId: 3, title: '你喜欢的歌曲'}, { id: Math.random() * 100000 >> 0, option: '歌曲3', questionId: 3, title: '你喜欢的歌曲'}];// 给相同题目分类// 给相同题目分类var categories = {};questions.forEach(function (item, i) { if (!categories[item.questionId]) { categories[item.questionId] = [item]; } else { categories[item.questionId].push(item); }});console.log(JSON.stringify(categories, 0, 2));// {// "1": [// {// "id": 76350,// "option": "x",// "questionId": 1,// "title": "你的名字"// }// ],// "2": [// {// "id": 42682,// "option": "动作1",// "questionId": 2,// "title": "你喜欢的动作"// },// {// "id": 19378,// "option": "动作2",// "questionId": 2,// "title": "你喜欢的动作"// },// {// "id": 25613,// "option": "动作3",// "questionId": 2,// "title": "你喜欢的动作"// },// {// "id": 25020,// "option": "动作4",// "questionId": 2,// "title": "你喜欢的动作"// },// {// "id": 70897,// "option": "动作5",// "questionId": 2,// "title": "你喜欢的动作"// }// ],// "3": [// {// "id": 38775,// "option": "歌曲1",// "questionId": 3,// "title": "你喜欢的歌曲"// },// {// "id": 50039,// "option": "歌曲2",// "questionId": 3,// "title": "你喜欢的歌曲"// },// {// "id": 71712,// "option": "歌曲3",// "questionId": 3,// "title": "你喜欢的歌曲"// }// ]// }对相同类型的题目进行遍历,后面的都放到第一个里面即可。并重新按照原格式存放// 用于按照原格式存放最后的数据var data =[];for (var key in categories) { var i, l; if (categories.hasOwnProperty(key)) { for (i = 1; i < categories[key].length; ++i) { // 第一个的值 = ',' + 下一个的值 categories[key][0].option += ',' + categories[key][i].option; // 删除下一个 categories[key].splice(i, 1); --i; } data.push(categories[key][0]); }}console.log('categories',JSON.stringify(categories, null, 2));console.log('data',JSON.stringify(data, null, 2));// 'categories' {// "1": [// {// "id": 72749,// "option": "x",// "questionId": 1,// "title": "你的名字"// }// ],// "2": [// {// "id": 33498,// "option": "动作1,动作2,动作3,动作4,动作5",// "questionId": 2,// "title": "你喜欢的动作"// }// ],// "3": [// {// "id": 79801,// "option": "歌曲1,歌曲2,歌曲3",// "questionId": 3,// "title": "你喜欢的歌曲"// }// ]// }// 'data' [// {// "id": 72749,// "option": "x",// "questionId": 1,// "title": "你的名字"// },// {// "id": 33498,// "option": "动作1,动作2,动作3,动作4,动作5",// "questionId": 2,// "title": "你喜欢的动作"// },// {// "id": 79801,// "option": "歌曲1,歌曲2,歌曲3",// "questionId": 3,// "title": "你喜欢的歌曲"// }// ]