JSFiddle - React, Tailwind, and code Playground
by Gerald Gillespie
JavaScript
const submitData = {
serviceVersion: '1.0',
//part is an array of objects. each object is similar
partsType: {
eachPart: [{
PartsType2: 'install',
PartNumber: 'A-123',
//...
}, {
PartsType2: 'remove',
PartNumber: 'A-123',
// ...
}],
neverHappening: 'foobar'
}
}
const meta = new Map();
meta.set('serviceVersion', {
dataType: 'STRING',
otherattribute : 'blah'
});
meta.set('partsType', {
dataType: 'COMPLEX'
});
meta.set('eachPart', {
dataType: 'COMPLEX'
});
meta.set('PartsType2', {
dataType: 'STRING'
});
meta.set('PartNumber', {
dataType: 'STRING'
});
meta.set('neverHappening', {
dataType: 'STRING'
});
console.log([...meta.keys()]);
class XMLParser {
_meta = meta;
constructor(meta) {
this.XMLNodeStrings = [];
this.meta = meta
}
transformData(data) {
//looping through all the possible meta keys will also loop through all data key
[...this.meta.keys()].forEach(metaKey => {
//ignore keys missing from data;
if (data[metaKey] === undefined) {
return;
}
// for (metaKey in this.meta) {
const _meta = this.meta.get(metaKey);
this.parseElement(data[metaKey], metaKey, _meta.dataType);
});
}
parseElement(subData, element, datatype, wrapperElement) {
let wrapper = [];
if (wrapperElement) {
wrapper = [`<${wrapperElement}>`, `<${wrapperElement}>`];
}
if (datatype === 'STRING') {
this.XMLNodeStrings.push(`<${element}>${subData}</${element}>`);
} else if (datatype === 'COMPLEX') {
//data will be an object or an array
//recursion
this.XMLNodeStrings.push(`<${element}>`);
if (Array.isArray(subData)) {
/*
subData = [{}...{}]
*/
console.log('skipping arrays for now','subData:', subData);
subData.forEach(sub => {
const _subXML = new XMLParser(this.meta);
const _xml = _subXML.transformData(sub);
...