gpt4 book ai didi

javascript - 反向映射 JSON 数据?

转载 作者:行者123 更新时间:2023-11-29 17:52:36 24 4
gpt4 key购买 nike

我被困在一个可能很简单的任务上,但找不到任何解决方案。我有一些 JSON 数据 - 让我们说:

[{
"_id": 1,
"type": "person",
"Name": "Hans",
"WorksFor": ["3", "4"]
}, {
"_id": 2,
"type": "person",
"Name": "Michael",
"WorksFor": ["3"]
}, {
"_id": 3,
"type": "department",
"Name": "Marketing"
}, {
"_id": 4,
"type": "department",
"Name": "Sales"
}]

据我了解here使用部门的映射数组将所有人员和他们工作的部门聚集在一起非常简单。然后我可以将相应的部门映射到 Person 并收到如下内容:

[{
"_id": 1,
"type": "person",
"Name": "Hans",
"WorksFor": ["3", "4"],
"Readable": ["Marketing", "Sales"]
}, {
"_id": 2,
"type": "person",
"Name": "Michael",
"WorksFor": ["3"],
"Readable": ["Sales"]
}]

但是对于另一个接口(interface),我需要“反过来”的数据,例如

[{
"_id": 3,
"type": "department",
"Name": "Marketing",
"employees": [
"Hans", "Michael"
]
}, {
"_id": 4,
"type": "department",
"Name": "Sales",
"employees": [
"Hans"
]
}]

有什么好的方法可以实现这个结构吗?两天的尝试并没有让我取得任何进展...

最佳答案

var data = [{ "_id": 1, "type": "person", "Name": "Hans", "WorksFor": ["3", "4"] }, { "_id": 2, "type": "person", "Name": "Michael", "WorksFor": ["3"] }, { "_id": 3, "type": "department", "Name": "Marketing" }, { "_id": 4, "type": "department", "Name": "Sales" }];

var departments = [],
persons = [];

data.forEach(e => {
if (e.type === "person") {
persons.push(e);
} else if (e.type === "department") {
departments.push(e);
e.employees = [];
}
});

departments.forEach(d => {
var workers = persons.filter(p => p.WorksFor.indexOf(d._id.toString()) > -1)
/*.map(p => p.Name)*/ // add this if you only need the name instead of the complete "person"

d.employees = d.employees.concat(workers);
});

console.log(JSON.stringify(departments, null, 4));

关于javascript - 反向映射 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42019461/

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