对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
]
}
];
我使用了Lodashgroupby方法,该方法以接近我期望的格式对项进行分组,但不完全是我想要的最终结果。Lotash结果为:
[
[
{ "tableName": 'table1',
"dataId": '1',
"header": 'firstHeader',
"rows": ["a","b","c"]
},
{ "tableName": 'table1',
"dataId": '1',
"header": 'secondHeader',
"rows": ["d","e","f"]
}
],
[
{ "tableName": 'table2',
"dataId": '2',
"header": 'aNewFirstHeader',
"rows": [1,2,3] },
]
]
最终,我要寻找的是最终结果:
[
{
"tableName": "table1",
"column": ["firstHeader", "secondHeader"],
"rows": [["a","b","c"], ["d","e","f"]]
},
{
"tableName": "table2",
"column": ["aNewFirstHeader"],
"rows": [[1,2,3]]
}
]
有没有不同的方法来使用groupBy方法,或者可能是仅使用javascript方法来获得我正在寻找的最终结果?
解决方案
通过使用reduce
和findIndex
,我们可以在O(N)时间内重建适合您格式的新数组。
data.reduce((arr, record) => {
const index = arr.findIndex((inside) => (inside.tableName === record.tableName));
if (index === -1) {
arr.push({
tableName: record.tableName,
column: [record.column],
rows: [record.rows]
})
} else {
arr[index].column.push(record.column);
arr[index].rows.push(record.rows);
}
return arr;
}, []);
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
]
}
];
const newData = data.reduce((arr, record) => {
const index = arr.findIndex((inside) => (inside.tableName === record.tableName));
if (index === -1) {
arr.push({
tableName: record.tableName,
column: [record.column],
rows: [record.rows]
})
} else {
arr[index].column.push(record.column);
arr[index].rows.push(record.rows);
}
return arr;
}, []);
console.log(newData);
相关文章