【发布时间】:2020-04-14 08:30:23
【问题描述】:
我正在尝试处理需要以多种方式更改的 json 数据。
我当前的 json 数据如下:
{
"file1": {
"function1": {
"calls": {
"105:4": {
"file": "file2",
"function": "function5"
},
"106:4": {
"file": "file2",
"function": "function6"
}
},
"lines1": {
"123": "102:0",
"456": "105:8"
},
"lines2": {
"102:0": [
"102:0"
],
"105:4": [
"106:4",
"107:1"
],
"106:4": [
"107:1"
]
}
}
}
}
但我希望数据如下:
{
"name": "program",
"children": [
{
"name": "file1",
"children": [
{
"name": "function1",
"calls": [
{
"line": 105,
"file": "file2",
"function": "function5"
},
{
"line": 106,
"file": "file2",
"function": "function6"
}
],
"lines1": [
102,
105
],
"lines2": [
[
102,
102
],
[
105,
106,
107
],
[
106,
107
]
],
"group": 1
}
],
"group": 1
}
],
"group": 0
}
这里,文件和函数的数量更多。名字的值是用户定义的。组信息取决于父子。每个文件将有一个组升序组号,文件内的所有函数也将具有相同的组号。对于行的值,取 : 之前的第一部分(104:4 变为 104)。
到目前为止,我已尝试使用以下代码,该代码不完整且未正确处理组信息。
function build(data) {
return Object.entries(data).reduce((r, [key, value], idx) => {
const obj = {
name: 'program',
children: [],
group: 0,
lines: []
}
if (key !== 'lines2) {
obj.name = key;
obj.children = build(value)
if(!(key.includes(":")))
obj.group = idx + 1;
} else {
if (!obj.lines) obj.lines = [];
Object.entries(value).forEach(([k, v]) => {
obj.lines.push([k, ...v].map(e => e.split(':').shift()))
})
}
r.push(obj)
return r;
}, [])
}
const result = build(data);
console.log(result);
如果您能帮助我,我将不胜感激。提前感谢您的宝贵时间。
【问题讨论】:
标签: javascript arrays json object mapping