I have a json data that I want to reformat into new key-value pairs. I am using following javascript code to format my json data.
const input = {
"file1": {
"function1": {
"calls": {
"405:4": {
"file": "file1",
"function": "function2"
},
"406:4": {
"file": "file1",
"function": "function3"
}
}
},
"function2": {
"calls": {
"397:7": {
"file": "file2",
"function": "function1"
}
}
},
"function3": {
"calls": null
},
"function4": {
"calls": null
}
},
"file2": {
"function5": {
"calls": {
"43:4": {
"file": "file2",
"function": "function5"
}
}
},
"function6": {
"calls": {
"32:4": {
"file": "file1",
"function": "function1"
}
}
}
}
}
function transformData(data) {
let res = [];
let calls = [];
Object.entries(data).map(([fileName, fileObject]) => {
Object.entries(fileObject).map(([functionName, functionObject]) => {
Object.entries(functionObject).map(([functionKey, functionValue]) => {
if(functionKey === "calls") {
Object.entries(functionValue).map(([callKey, callObject]) => {
calls = [...calls, callObject['file']+"."+callObject['function']]
});
}
});
res = [...res,{"name": fileName+"."+functionName, "import": calls}]
});
});
return res;
}
const sanitize = (obj) => {
return JSON.parse(JSON.stringify(obj, (key, value) => {
return (value === null ? undefined : value);
}));
};
const data = sanitize(input)
const result = transformData(data);
console.log(result)
My expected json data is following:
[
{
"name": "file1.function1",
"imports": [
"file1.function2",
"file1.function3"
]
},
{
"name": "file1.function2",
"imports": [
"file2.function1"
]
},
{
"name": "file1.function3",
"imports": []
},
{
"name": "file1.function4",
"imports": []
},
{
"name": "file2.function5",
"imports": [
"file2.function5"
]
},
{
"name": "file2.function6",
"imports": [
"file1.function1"
]
}
]
My output is not correct. Though its giving right amount of main array with name and imports keys but the import array is wrong.
Can someone please help me. I think i'm not returning it in the correct way.