gpt4 book ai didi

javascript - 需要帮助使用 lodash 来重组具有新结构的数组

转载 作者:行者123 更新时间:2023-12-03 10:34:41 24 4
gpt4 key购买 nike

我有一个从 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 的新手,我已经花了几个小时探索了一些尚未解决的兔子洞。我意识到是时候向专家求助了。关于如何获得上面显示的最终结果有什么建议吗?

感谢您的帮助!

最佳答案

您可以使用reduce()来循环并构建新的响应:

  _.values( _.reduce([{
"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"
}], function(a, b) {

// create a new array for common items under InsightId:
var temp=a[b.InsightId] = a[b.InsightId] || {
InsightId: b.InsightId,
Classification: b.Classification,
Attributes: []
};

// push current attribs into collection under InsightId:
temp.Attributes.push({
AttributeId: b.AttributeId,
InsightAttribute: b.InsightAttribute,
AttributeType: b.AttributeType
});
return a;
}, {}));

返回:

[
{
"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"
}
]
}
]

可能有一种稍微简单的方法来收集属性,但只有 3 个键,硬编码并不太麻烦。

关于javascript - 需要帮助使用 lodash 来重组具有新结构的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29055671/

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