Currently, I have a JSON dataset that needs to be reformatted into a different structure.
This is the original JSON data:
{
"info": {
"file1": {
"book1": {
"lines": {
"102:0": [
"102:0"
],
"105:4": [
"106:4"
],
"106:4": [
"107:1",
"108:1"
]
}
}
}
}
}
The desired mapping looks like this:
{
"name": "main",
"children": [
{
"name": "file1",
"children": [
{
"name": "book1",
"group": "1",
"lines": [
"102",
"102"
],
[
"105",
"106"
],
[
"106",
"107",
"108"
]
}
],
"group": 1,
}
],
"group": 0
}
However, I anticipate having more files and books in the future. In the lines section, the first part (before the colon) between quotes is extracted ("106:4" becomes "106"). The number from the key comes first, followed by numbers from the corresponding values forming a list (["106", "107", "108"]). The group information relies on parent-child relationships where the first level parent is group 0 and so forth. The initial name ("main") is also user-defined.
So far, I have attempted the following code snippet:
function build(data) {
return Object.entries(data).reduce((r, [key, value], idx) => {
//const obj = {}
const obj = {
name: 'main',
children: [],
group: 0,
lines: []
}
if (key !== 'reduced control flow') {
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);
The issue lies in the generation of correct group information. I am currently exploring ways to resolve this problem and would greatly appreciate any assistance you can offer.