gpt4 book ai didi

javascript - 将js对象转换为层次结构的JSON结构

转载 作者:行者123 更新时间:2023-11-28 17:08:55 25 4
gpt4 key购买 nike

我必须创建一个 JavaScript 函数来将如下所示的对象转换为分层 JSON 对象。

来源是 HR 员工列表及其相应的经理。

源对象:

Employee    Manager Title
Alfredo general manager
Bergman Alfredo senior engineer
Billy Alfredo senior engineer
Johnson Alfredo department manager
Angela Johnson senior engineer
Anderson Johnson senior engineer
Amy Johnson department manager
Patsy Amy engineer
Jane Amy engineer

JSON 对象应如下所示:

var datasource = {
'name': 'Alfredo',
'title': 'general manager',
'children': [
{ 'name': 'Bergman', 'title': 'senior engineer' },
{ 'name': 'Johnson', 'title': 'department manager',
'children': [
{ 'name': 'Anderson', 'title': 'senior engineer' },
{ 'name': 'Amy', 'title': 'department manager',
'children': [
{ 'name': 'Patsy', 'title': 'engineer'},
{ 'name': 'Jane', 'title': 'engineer'}
]
},
{ 'name': 'Angela', 'title': 'senior engineer' }
]
},
{ 'name': 'Billy', 'title': 'senior engineer' }
]
};

我尝试过各种方法都不成功,但我对 JavaScript 很菜鸟。

任何帮助或想法将不胜感激。

最佳答案

我认为这应该做你想做的事:迭代列表,构建所有员工的 map ,然后按经理姓名将员工分类到正确的子组中,仅返回符合条件的员工没有经理。

var entries = [{ name: 'Bergman', manager: 'Alfredo', title: 'senior engineer' }, { name: 'Billy', manager: 'Alfredo', title: 'senior engineer' }, { name: 'Johnson', manager: 'Alfredo', title: 'department manager' }, { name: 'Angela', manager: 'Johnson', title: 'senior engineer' }, { name: 'Anderson', manager: 'Johnson', title: 'senior engineer' }, { name: 'Amy', manager: 'Johnson', title: 'department manager' }, { name: 'Patsy', manager: 'Amy', title: 'engineer' }, { name: 'Jane', manager: 'Amy', title: 'engineer' }, { name: 'Alfredo', manager: '', title: 'general manager' }]
function build_org_chart(list) {
var map = {}, node, managers = [], i;

// Build the map of employees we will use later.
for (i = 0; i < list.length; i += 1) {
map[list[i].name] = i;
list[i].directReports = []; // init the children
}

for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.manager != "") {

// If the employee has a manager, find them
var indexOfManager = map[node.manager];

// Then add that employee to the managers children.
list[indexOfManager].directReports.push(node);
} else {

// If they haven't got a manager, must be a boss.
managers.push(node);
}
}

// Return only the top bosses.
return managers;
}

console.log(build_org_chart(entries));

关于javascript - 将js对象转换为层次结构的JSON结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55023378/

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