Skip to content

Instantly share code, notes, and snippets.

@Azer5C74
Last active June 5, 2022 11:02
Show Gist options
  • Save Azer5C74/e0dea5f7c0daccb4f0514cf26026737f to your computer and use it in GitHub Desktop.
Save Azer5C74/e0dea5f7c0daccb4f0514cf26026737f to your computer and use it in GitHub Desktop.
Recursively manipulate mock json server
[
{
"id": 0,
"title": "1",
"sublist": [
{
"id": 1,
"title": "1.1",
"sublist": [
{
"id": 2,
"title": "1.1.1",
"sublist": []
},
{
"id": 3,
"title": "1.1.2",
"sublist": []
}
]
},
{
"id": 4,
"title": "1.2",
"sublist": []
},
{
"id": 5,
"title": "1.3",
"sublist": [
{
"id": 6,
"title": "1.3.1",
"sublist": [
{
"id": 7,
"title": "1.3.1.1",
"sublist": []
},
{
"id": 8,
"title": "1.3.1.2",
"sublist": []
}
]
},
{
"id": 9,
"title": "1.3.2",
"sublist": []
},
{
"id": 10,
"title": "1.3.3",
"sublist": []
}
]
},
{
"id": 11,
"title": "1.4",
"sublist": []
}
]
},
{
"id": 12,
"title": "2",
"sublist": [
{
"id": 13,
"title": "2.1",
"sublist": []
},
{
"id": 14,
"title": "2.2",
"sublist": []
},
{
"id": 15,
"title": "2.3",
"sublist": []
},
{
"id": 16,
"title": "2.4",
"sublist": []
},
{
"id": 17,
"title": "2.5",
"sublist": [
{
"id": 18,
"title": "2.6",
"sublist": [
{
"id": 19,
"title": "2.6.1",
"sublist": []
},
{
"id": 20,
"title": "2.6.2",
"sublist": []
},
{
"id": 21,
"title": "2.6.3",
"sublist": [
{
"id": 22,
"title": "2.6.3.1",
"sublist": [
{
"id": 23,
"title": "2.6.3.1.1",
"sublist": []
},
{
"id": 24,
"title": "2.6.3.1.2",
"sublist": []
}
]
},
{
"id": 25,
"title": "2.6.4",
"sublist": []
}
]
}
]
}
]
}
]
},
{
"id": 26,
"title": "3",
"sublist":[]
},
{
"id":27,
"title": "4",
"sublist":[]
}
]
const content = require(`./inputdata.json`);
const fs = require('fs')
let outputdata = content
let i = 0;
function NestedChaps(chapter) {
chapter.id = i; // adding "id" attribute to all of the objects
i = i + 1;
console.log("id:" + chapter.id + "," + "title:" + chapter.title)
const nestedChaps = (chapter.sublist || []).map((subchapter, k) => {
return (
NestedChaps(subchapter)
)
}
)
nestedChaps;
}
outputdata.map((chapter, i) => {
return (
NestedChaps(chapter)
)
}
)
fs.writeFileSync('outputdata.json', JSON.stringify(outputdata)); // writing the result to new file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment