gpt4 book ai didi

javascript - 对 Javascript 数组进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:48 25 4
gpt4 key购买 nike

我试图从一个数组中获取数据,按对象属性对数据进行分组,然后将其发送到一个新数组。当前的数据格式如下:

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
]
}
];

我使用了 Lodash groupby方法,它以接近我期望的格式对项目进行分组,但不完全是我想要的最终结果。 lodash结果是:

[
[
{ "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 的方法来获得我正在寻找的最终结果?

最佳答案

通过使用 reducefindIndex,我们可以在 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);

关于javascript - 对 Javascript 数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com