I wrote some code to create arrays of objects in js files based on data in txt files as follows:
var num1 = ['100', '200', '500', '1000']
var num2 = ['10', '20', '30', '40', '50']
for (var i of num1) {
for (var j of num2) {
var source = './dat/txt/data_' + i + '_' + j + '.txt'
var dest = './dat/js/data_' + i + '_' + j + '.js'
var write = '[\n'
fs.readFile(source, 'utf-8', function (err, data) {
if (err) {
console.log(err)
}
var datArray = data.split('\r\n')
for(let k=0;k<parseInt(i);k++){
var numbers = datArray[k].split(' ')
write = write.concat('{\npos:\nx:',numbers[0],',\ny:',numbers[1],'\n},\nbeta:',numbers[2],'\n},')
}
})
fs.writeFile(dest, write, (err) => {
if (err) {
console.log(err)
} else console.log('Written successfully')
})
}
}
The txt files have the format as follow:
1 2 3
1 2 3
1 2 3
....
And I want to create Arrays of objects as follow:
[
{
pos: {
x: 1,
y: 2,
},
beta: 3
},
...
]
When I run the code, it has this Error:
var numbers = datArray[k].split(' ')
TypeError: Cannot read properties of undefined (reading 'split')
I tried log the array datArray and it's a normal Array of Strings, and the length of datArray equals value of i. The output files also only write a single character '[' and a line break. What am I doing wrong here?
i think to solve this problem change this line:
var numbers = datArray[k].split(' ')
with this :
var numbers = datArray[k]?.split(' ')