I'm trying to create an object of objects in JS but I think I have some problems with the asynchronous execution.
Here is my code:
// Extract data (episode number, characters firstname's) from .docx to JSON
var mammoth = require("mammoth")
function docx2Object (filepath) {
return mammoth.extractRawText({path: filepath})
.then(function (res) {
return res.value;
})
.then(function (res) {
let arr = {}
arr["number"] = "" + res.match(/(?!Episode #)\d+/)
arr["names"] = [...new Set(res.match(/^[^:\r\n]+(?=:)/gm))]
return arr
})
}
function files2JSON (arrayScripts) {
let arr = {}
let i = 0
arrayScripts.forEach(function(element) {
docx2Object(element).then(function (res) {
arr[i++] = res
console.log(JSON.stringify(arr, null, '\t'))
})
})
return JSON.stringify(arr, null, '\t')
}
let arrayScripts = ["doc1.docx", "doc2.docx"]
console.log(files2JSON(arrayScripts))
And here is the output:
{}
{
"0": {
"number": "10600",
"names": [
"Hilary",
"Jean-Claude",
"Devon",
"Jean Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
}
}
{
"0": {
"number": "10600",
"names": [
"Hilary",
"Jean-Claude",
"Devon",
"Jean Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
},
"1": {
"number": "10601",
"names": [
"Hilary",
"Devon",
"Jean+Claude",
"Jean + Claude",
"Jean/Claude",
"Jean / Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
}
}
My array is empty and my indexes do not match.Can anyone help?