假设我们有一个像这样的JavaScript数组-
const data = [ { "dataId": "1", "tableName": "table1", "column": "firstHeader", "rows": [ "a","b","c" ] }, { "dataId": "2", "tableName": "table1", "column": "secondHeader", "rows": [ "d","e","f", ] }, { "dataId": "3", "tableName": "table2", "column": "aNewFirstHeader", "rows": [ 1,2,3 ] } ];
我们需要在一个这样的数组中编写一个JavaScript函数。该函数应基于原始数组构造一个新的对象分组数组。
分组数组应将单独的唯一“ tableName”对象的数据包含在其自己的对象中。
因此,最终输出应类似于-
const output = [ { "tableName": "table1", "column": ["firstHeader", "secondHeader"], "rows": [["a","b","c"], ["d","e","f"]] }, { "tableName": "table2", "column": ["aNewFirstHeader"], "rows": [[1,2,3]] } ];
const arr = [ { "dataId": "1", "tableName": "table1", "column": "firstHeader", "rows": [ "val","b","c" ] }, { "dataId": "2", "tableName": "table1", "column": "secondHeader", "rows": [ "d","e","f", ] }, { "dataId": "3", "tableName": "table2", "column": "aNewFirstHeader", "rows": [ 1,2,3 ] } ]; const groupArray = (arr = []) => { const res = arr.reduce((obj => (acc, val) => { let item = obj.get(val.tableName); if (!item) { item = { tableName: val.tableName, column: [], rows: [] } obj.set(val.tableName, item); acc.push(item); }; item.column.push(val.column); item.rows.push(val.rows); return acc; })(new Map), []); return res; }; console.log(JSON.stringify(groupArray(arr), undefined, 4));
输出结果
控制台中的输出将是-
[ { "tableName": "table1", "column": [ "firstHeader", "secondHeader" ], "rows": [ [ "val", "b", "c" ], [ "d", "e", "f" ] ] }, { "tableName": "table2", "column": [ "aNewFirstHeader" ], "rows": [ [ 1, 2, 3 ] ] } ]