【发布时间】:2022-01-19 14:20:15
【问题描述】:
我正在寻找一种方法将以下数据结构深度合并到 Javascript 中的唯一对象数组中。
我已经探索过 lodash、reducers 等,只能唯一地合并第一个嵌套级别。
从这种格式开始:
[
"/Apparel",
"/Apparel/Jewelry",
"/Apparel/Jewelry/Rings",
"/Apparel/Jewelry/Precious & Semi-Precious Gems & Gemstone Jewelry",
"/Apparel/Jewelry/Rings/Engagement Rings",
"/Apparel/Jewelry/Precious & Semi-Precious Gems & Gemstone Jewelry/Diamond Jewelry"
]
我已经得出以下数据结构:
[
{
"Occasions & Gifts": {}
},
{
"Apparel": {}
},
{
"Apparel": {
"Clothing": {}
}
},
{
"Occasions & Gifts": {
"Special Occasions": {
"Weddings": {}
}
}
},
{
"Apparel": {
"Clothing": {
"Women's Clothing": {
"Dresses": {}
}
}
}
},
{
"Apparel": {
"Clothing": {
"Formal Wear": {}
}
}
},
{
"Apparel": {
"Clothing": {
"Formal Wear": {
"Bridal Wear": {}
}
}
}
},
{
"Occasions & Gifts": {
"Special Occasions": {}
}
},
{
"Apparel": {
"Clothing": {
"Women's Clothing": {}
}
}
}
]
通过对这些独特的深度合并,我应该拥有一个可以使用并迭代以显示在前端的数据结构。
上述的理想输出是:
{
"Occasions & Gifts": {
"Special Occasions": {
"Weddings": {}
}
}
},
{
"Apparel": {
"Clothing": {
"Women's Clothing": {
"Dresses": {}
}
"Formal Wear": {
"Bridal Wear": {}
}
}
}
}
]
甚至更好的是:
[
{
"title": "Apparel",
"subTerms": [
{
"title": "Jewellery",
"subTerms": [
{
"title": "Rings",
"subTerms": [
{
"title": "Engagement Rings",
"subTerms": []
}
]
}
]
},
{
"title": "Precious & Semi-Precious Gems & Gemstone Jewelry",
"subTerms": [
{
"title": "Diamond Jewelry",
"subTerms": []
}
]
}
]
}
]
【问题讨论】:
-
不清楚是哪种逻辑将您从第一个数组带到最终结果。例如:原来的数组没有“婚礼”,却突然出现了。请给出一个一致的输入示例 - 预期输出,并解释逻辑是什么。
-
标题与“甚至更好”的预期输出无关。你有一个路径数组,你想把它们转换成一个对象。
标签: javascript arrays data-structures javascript-objects