我正在寻找一种功能性的解决方案,将这个对象映射到一个层次结构中,按实践,主题区和资产分组,以便这个对象:
var data = {
"research": [
{ "practice": "Talent Management", "id": "20992", "title": "Creating a Culture of Leadership", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20993", "title": "Talent Economics", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20990", "title": "Finding the Right Talent", "subjectArea": "Recruiting" },
{ "practice": "Human Resources", "id": "20994", "title": "Tips from the Front", "subjectArea": "HR Training" },
{ "practice": "Human Resources", "id": "20995", "title": "Reward Programs", "subjectArea": "Employee Engagement" },
]
}
转换为此(计算练习的项目数量,并将练习的主题区域添加为儿童,计算练习中主题区域的项目数量,并将资产(ID和标题)添加为子项对于主题领域):
{
"name": "research",
"children": [
{
"name": "Talent Management", "size": 3, "children": [
{
"name": "Talent Strategy", "size": 2, "children": [
{ "name": "Creating a Culture of Leadership", "id": "20992", "size": 1 },
{ "name": "Talent Economics", "id": "20993", "size": 1 }
]
},
{
"name": "Recruiting", "size": 1, "children": [
{ "title": "Finding the Right Talent", "id": "20990", "size": 1 },
]
}
]
},
{
"name": "Human Resources", "size": 2, "children": [
{
"name": "HR Training", "size": 1, "children": [
{ "name": "Tips from the Front", "id": "20994", "size": 1 },
]
},
{
"name": "Employee Engagement", "size": 1, "children": [
{ "name": "Reward Programs", "id": "20995", "size": 1 },
]
}
]
},
]
}
我无法整理地图并减少组合以使用计数产生正确的结果,并欣赏任何洞察力。
答案 0 :(得分:0)
它可能不是SO的原因(根据上面的评论),但是如果有人需要将平面对象数组转换为层次结构,您只需指定嵌套顺序,级别数和字段名称,这是一个递归函数 - https://github.com/lance-p/configurable-transform-flat-array-to-nested。希望它可能对其他人有帮助。