gpt4 book ai didi

javascript - 使用 lodash 进行嵌套数组分组

转载 作者:行者123 更新时间:2023-12-03 01:58:46 25 4
gpt4 key购买 nike

我有一个小型网络应用程序,它使用 API 调用获取数据,响应是报告数组,每个报告都有唯一的 ID、应用程序、类型和标题。

我想通过按应用程序分组然后按类型将其映射到新对象如下所述。

输入:

[
{
"id": "REPORT1",
"application": "APP1",
"type": "TYPE1",
"title": ""
},
{
"id": "REPORT2",
"application": "APP1",
"type": "TYPE1",
"title": ""
},
{
"id": "REPORT3",
"application": "APP1",
"type": "TYPE2",
"title": ""
},
{
"id": "REPORT4",
"application": "APP2",
"type": "TYPE3",
"title": ""
}
]

期望的输出:

{
"APP1": {
"TYPE1": [
{
"id": "REPORT1",
"application": "APP1",
"type": "TYPE1",
"title": ""
},
{
"id": "REPORT2",
"application": "APP1",
"type": "TYPE1",
"title": ""
}
],
"TYPE2": [
{
"id": "REPORT3",
"application": "APP1",
"type": "TYPE2",
"title": ""
}
]
},
"APP2": {
"TYPE3": [
{
"id": "REPORT4",
"application": "APP2",
"type": "TYPE3",
"title": ""
}
]
}
}

通过 loadash 我想出了这个:

const output = _(input)
.groupBy(report => report.application)
.value()

application分组后,我需要按type进行另一个嵌套分组或映射,但陷入困境。

最佳答案

这可以很容易地实现,无需 lodash,通过 the Array#reduce() function

有关如何实现的详细信息,请参阅代码片段源代码中的注释:

var input = [{
"id": "REPORT1",
"application": "APP1",
"type": "TYPE1",
"title": ""
},
{
"id": "REPORT2",
"application": "APP1",
"type": "TYPE1",
"title": ""
},
{
"id": "REPORT3",
"application": "APP1",
"type": "TYPE2",
"title": ""
},
{
"id": "REPORT4",
"application": "APP2",
"type": "TYPE3",
"title": ""
}
];

var output = input.reduce((result, item) => {

// Get app object corresponding to current item from result (or insert if not present)
var app = result[item.application] = result[item.application] || {};

// Get type array corresponding to current item from app object (or insert if not present)
var type = app[item.type] = app[item.type] || [];

// Add current item to current type array
type.push(item);

// Return the result object for this iteration
return result;

}, {});

console.log(output);
.as-console-wrapper {
height:100% !important;
max-height:unset !important;
}

关于javascript - 使用 lodash 进行嵌套数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929908/

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