如何通过循环对象来创建新行



我正在使用Electron和docx模块动态创建一个包含用户提供的数据的docx文件。

我目前在构建一个由一个对象的行组成的段落时遇到了问题,我从一开始就不知道它会有多少数据。

对象是这样的,目前只有2条信息。

"opuses": [
{
"writer": "Adolphe C. Adam",
"opus": "Concerto"
},
{
"writer": "Adams John",
"opus": "Short ride in a fast machine"
}
]
}

我试了很多方法,但似乎都不起作用。非常感谢!

const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
alignment: AlignmentType.JUSTIFIED,
children: [
new TextRun({
text: '// HERE IS WHERE I WANT TO BE THE LINES, CURRENTLY, TWO NEW LINES // ',
bold: true,
size: 24
})
// OR HERE AS NEW TextRuns FOR EACH LINE//
],
}) 
}]
})

--更新:预期的结果就像我写的那样:

. . .
new TextRun({
text: 'Adolphe C. Adam > Concerto',
bold: true,
size: 24
}),
new TextRun({
text: 'Adams John > Short ride in a fast machine',
bold: true,
size: 24
}),
. . .

(我已经尝试过先制作循环字符串,然后将其传递到TextRun的文本中,但"\n"不起作用,它只是一个长字符串(

我相信你可以这样做——运行一个array.map(),它将返回所有作品的数组。

const data = {
"opuses": [{
"writer": "Adolphe C. Adam",
"opus": "Concerto"
},
{
"writer": "Adams John",
"opus": "Short ride in a fast machine"
}
]
}
const opuses = data.opuses.map(o => (new TextRun({
text: o.writer + ' > ' + o.opus,
bold: true,
size: 24
})));
const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
alignment: AlignmentType.JUSTIFIED,
children: opuses,
})
}]
})

const data = {
"opuses": [{
"writer": "Adolphe C. Adam",
"opus": "Concerto"
},
{
"writer": "Adams John",
"opus": "Short ride in a fast machine"
}
]
}
// this isjust here for testing
class TextRun {
constructor(obj) {
this.obj = obj;
}
}
const opuses = data.opuses.map(o => (new TextRun({
text: o.writer + ' > ' + o.opus,
bold: true,
size: 24
})));
console.log(opuses)

最新更新