对 JavaScript 数组进行分组
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的 JavaScript 数组 −
const data = [ { &"dataId": &"1", &"tableName": &"table1", &"column": &"firstHeader", &"rows": [ &"a&",&"b&",&"c&" ] }, { &"dataId&": &"2&", &"tableName&": &"table1&", &"column&": &"secondHeader&", &"rows&": [ "d";, ] }, { &"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 ] ] } ]