假设我们有两个不同的对象数组,其中包含有关某些人回答的问题的信息-
const arr1=[ { PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2', value: 'whatever' }, { PersonalID: '13', qusetionNumber: '3', value: 'anything' }, { PersonalID: '14', qusetionNumber: '4', value: 'null' } ]; const arr2=[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' }, {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'}, {qusetionNumber: '4', choiceID: '115', cValue: 'red'} ];
我们需要编写一个函数来对数据进行分组,并根据唯一身份的人在两个数组中显示该数据,即,一个对象描述每个唯一身份的人的问题和选择。
因此,最终输出应如下所示:
const output = [{ personalID:11, qusetionNumber:1, value: 'Something' }, { personalID:12, qusetionNumber:2, value: 'whatever', choice:[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' } ] }, { personalID:13, qusetionNumber:3, value: 'anything', choice:[ { qusetionNumber: '3', chID: '114', cValue: 'yellow' } ] }, { personalID:14, qusetionNumber:4, value: 'null', choice:[ { qusetionNumber: '4', chID: '115', cValue: 'red' } ] }];
为此的代码将是-
const arr1=[ { PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2', value: 'whatever' }, { PersonalID: '13', qusetionNumber: '3', value: 'anything' }, { PersonalID: '14', qusetionNumber: '4', value: 'null' } ]; const arr2=[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' }, {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'}, {qusetionNumber: '4', choiceID: '115', cValue: 'red'} ]; const mergeArray = (arr1 = [], arr2 = []) => { let i = -1; const copy = arr1.slice(); copy.forEach(obj => { const helper = []; arr2.forEach(obj2 => { if(obj.qusetionNumber == obj2.qusetionNumber){ i++; helper.push(arr2[i]); }; }) if(helper.length !== 0){ obj.choice = helper; }; }) return copy; }; console.log(JSON.stringify(mergeArray(arr1, arr2), undefined, 4));
输出结果
控制台中的输出将是-
[ { "PersonalID": "11", "qusetionNumber": "1", "value": "Something" }, { "PersonalID": "12", "qusetionNumber": "2", "value": "whatever", "choice": [ { "qusetionNumber": "2", "chID": "111", "cValue": "red" }, { "qusetionNumber": "2", "chID": "112", "cValue": "green" }, { "qusetionNumber": "2", "chID": "113", "cValue": "blue" } ] }, { "PersonalID": "13", "qusetionNumber": "3", "value": "anything", "choice": [ { "qusetionNumber": "3", "choiceID": "114", "cValue": "yellow" } ] }, { "PersonalID": "14", "qusetionNumber": "4", "value": "null", "choice": [ { "qusetionNumber": "4", "choiceID": "115", "cValue": "red" } ] } ]