I have the following object that I want to split in increments of 100 and save each 100 into separate files using Node.js. However, I am not able to find any way to split an array that has thousands of records by 100 and save into a separate file.
Question:
How can I split an object's array property by increments of 100 into separate files?
What I tried
var fs = require('fs');
var filePath = 'myPath.json';
fs.readFile(filePath, (err, data) => {
if(err) {
throw err;
}
let jsonObject = JSON.parse(data);
var numOfRecords = jsonObject.myRecords.length;
var numOfFilesRequired = Math.ceil(numOfRecords/100);
for(var num = 0; num < numOfFilesRequired; num++) {
var splitItems = jsonObject.slice(0, numOfRecords);
var newJsonObject = [];
newJsonObject.push({ myRecords : splitItems });
// this add additional [] to the beginning and end which I don't want
fs.writeFileSync('output.json', JSON.stringify(newJsonObject);
}
});
Sample data
{ myRecords : [
{ /* record 1*/},
{ /* record 2*/},
...
{ /* record 1000*/}
]
}
Expected output
- 10 files where 100 records are stored
myfile-1.json
contains records 1-100myfile-2.json
contains records 101-200myfile-3.json
contains records 201-300
Sample of the expected output file name: myfile-1.json
{
myRecords : [
{ /* record 1*/},
{ /* record 2*/},
...
{ /* record 100*/}
]
}