I am trying to work with a json data which needs to be changed in many ways.
My current json data is following:
{
"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"
]
}
}
}
}
But I want the data as following:
{
"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
}
Here, number of files and functions are more. The value of first name is user defined. The group information is depend on the parent-child. Each file will have a group ascending group number and all the functions inside the file will also have the same group number. For the values for lines the first part before : are taken (104:4 becomes 104).
I have tried with following code so far, which is incomplete and not handling group information correctly.
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);
I would really appreciate if you can help me out. Thanks in advance for your time.