【发布时间】:2021-10-25 03:15:39
【问题描述】:
我得到一个对象数组:
const inputStructure = [
{
state: 'LA',
insurance: 'Test1'
},
{
state: 'LA',
insurance: 'Test2'
},
{
state: 'TX',
insurance: 'Test3'
}
]
如何将具有相同state 属性的对象分组?
我需要创建一个返回以下结果的函数:
const outputStructure = {
'LA': {
state: 'LA',
insurances: ['Test1', 'Test2']
},
'TX': {
state: 'TX',
insurances: ['Test3']
}
}
【问题讨论】:
-
熟悉how to access and process nested objects, arrays or JSON以及如何使用create objects并使用
Object和Array的可用静态和实例方法。 -
您看过
map或reduce函数吗?这些方法将帮助您迭代结构并创建所需的新结构。 -
投票关闭作为副本。许多库都有一个
groupBy函数,并且很容易编写自己的函数,如副本所示。
标签: javascript algorithm