我正在尝试通过 2 个级联循环从 2 个 JSON 对象构建一个 xml 文件。在第二个循环中,我找不到如何从前一个循环传递一个值:
在下面的示例中,我想将“docnumber”值传递给我的第二个循环(通过 GroupsACLJSON),以便从第二个 JSON 对象构建“acl”节点,但使用父对象属性中的“this.docnumber”返回“未定义”,从而导致一个空的“acl”节点。
var documentsJSON = [{
"folder": "Enterprise1",
"extension": "DOCX",
"docnumber": "3912271",
"version": "1"
},
{
"folder": "Enterprise2",
"extension": "MSG",
"docnumber": "3912298",
"version": "1"
},
{
"folder": "Enterprise3",
"extension": "DOCX",
"docnumber": "3912692",
"version": "1"
}
]
var GroupsACLJSON = [{
"docNumber": "3912271",
"groupName": "group1"
},
{
"docNumber": "3912271",
"groupName": "group2"
},
{
"docNumber": "3912298",
"groupName": "group3"
},
{
"docNumber": "3912298",
"groupName": "group4"
}
]
// importing and declaring xmlbuilder variable:
var builder = require('xmlbuilder');
var xmlObjectImporter = builder.create('import', {
version: '1.0',
encoding: 'UTF-8',
standalone: true
}, {
headless: false,
stringify: {}
});
var nodeArray = [];
var xmlObjectElement = {
node: function() {
for (var i = 0; i < documentsJSON.length; i++) {
// populate the nodeObject for each row in documentsJSON and add it to the nodeArray:
var nodeObject = {
location: documentsJSON[i].folder,
category: {
attribute: [{
'#text': documentsJSON[i].docnumber,
'@name': "Document Number"
}],
'@name': "ACME",
},
docnumber: documentsJSON[i].docnumber,
// loop through GroupsACLJSON to find if we have specific ACL groups for this document:
acl: function() {
var documentNumber = this.docnumber
console.log(this.docnumber);
var acl = [];
var aclObject = {};
for (var j = 0; j < GroupsACLJSON.length; j++) {
if (GroupsACLJSON[j].docNumber == documentNumber) {
aclObject = {
'@group': GroupsACLJSON[j].groupName,
'@permissions': '111111100'
};
acl.push(aclObject);
};
};
return acl;
},
'@type': "document",
'@action': "create",
};
nodeArray.push(nodeObject);
};
return nodeArray;
}
};
// writing our elements in the xml file using the XML object:
var ele = xmlObjectImporter.ele(xmlObjectElement);
console.log(xmlObjectImporter.toString({
pretty: true
}));
这是我期望的输出:
<import>
<node type="document" action="create">
<location>Enterprise1</location>
<category name="ACME">
<attribute name="Document Number">3912271</attribute>
</category>
<docnumber>3912271</docnumber>
<acl group="group1" permissions="111111100" />
<acl group="group2" permissions="111111100" />
</node>
<node type="document" action="create">
<location>Enterprise2</location>
<category name="ACME">
<attribute name="Document Number">3912298</attribute>
</category>
<docnumber>3912298</docnumber>
<acl group="group3" permissions="111111100" />
<acl group="group4" permissions="111111100" />
</node>
<node type="document" action="create">
<location>Enterprise3</location>
<category name="ACME">
<attribute name="Document Number">3912692</attribute>
</category>
<docnumber>3912692</docnumber>
<acl/>
</node>
</import>