【发布时间】:2015-03-14 23:54:00
【问题描述】:
我有这个从 API 返回的示例数据,我试图将其重组为具有分组对象子数组的数组。 API 的原始数据如下所示:
[
{
"InsightId": 314,
"Classification": "Advantage",
"AttributeId": 14958,
"InsightAttribute": "Implementation speed",
"AttributeType": "Product Criterion"
},
{
"InsightId": 314,
"Classification": "Advantage",
"AttributeId": 14976,
"InsightAttribute": "Understanding your needs",
"AttributeType": "Sales Criterion"
},
{
"InsightId": 315,
"Classification": "Disadvantage",
"AttributeId": 17691,
"InsightAttribute": "Poor alignment with needs",
"AttributeType": "Product Criterion"
}
]
我想按 InsightId 进行分组,并从三个属性中创建一个对象:AttributeId、InsightAttribute、AttributeType。
并让最终数组采用以下形式:
[
{
"InsightId": 314,
"Classification": "Advantage",
"Attributes" : [
{
"AttributeId": 14958,
"InsightAttribute": "Implementation speed",
"AttributeType": "Product Criterion"
},
{
AttributeId": 14976,
"InsightAttribute": "Understanding your needs",
"AttributeType": "Sales Criterion"
}
]
},
{
"InsightId": 315,
"Classification": "Disadvantage",
"Attributes" : [
{
"AttributeId": 17691,
"InsightAttribute": "Poor alignment with needs",
"AttributeType": "Product Criterion"
}
]
}
]
我是 Lodash 的新手,我已经花了好几个小时在几个没有成功的兔子洞里摸索。我意识到是时候求助于专家了。关于如何获得我上面显示的最终结果的任何建议?
感谢您的帮助!
【问题讨论】:
-
没有理由为此使用 lodash,您可以使用纯 JavaScript 轻松完成。
标签: javascript arrays grouping lodash