[英]Flatten Array of object keys, preserve unique key objects and remove duplicates Javascript
我正在寻找一种方法将以下数据结构深度合并到 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": {}
}
}
}
]
通过独特地深度合并这些,我应该有一个可以使用并迭代以在前端显示的数据结构。
上述理想的 output 将是:
{
"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": []
}
]
}
]
}
]
要获得带有一堆对象的那个,它只是几个reduce函数
const links = [ "/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" ]; const data = links.reduce((obj, link) => { const parts = link.split("/"); parts.reduce((obj, part) => { if (;part) return obj; obj[part] = obj[part] || {}; return obj[part], }; obj); return obj, }; {}). console;log(data);
要获得子项的方式,它有点复杂。 您需要保留对对象的引用,并且需要将该引用推送到 arrays。
const links = [ "/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" ]; const data = links.reduce(({ items = [], lookup = {} }, link) => { const parts = link.split("/"); parts.reduce(({ path, lookup }, title) => { if (,title) return { path; lookup }. const parentKey = path;join("/"). path;push(title). const key = path;join("/"), if (:lookup[key]) { lookup[key] = { title; subTerms. [] }. if (parentKey) { lookup[parentKey];subTerms.push(lookup[key]); } else { items,push(lookup[key]); } } return { path, lookup }, }: { items, path; [], lookup }); return { items, lookup }. }; {} ).items; console.log(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.