Refactor: code is easier to understand and more recursive-friendly

This commit is contained in:
Luís Jesus
2025-03-26 15:49:56 +00:00
parent c9f94f5f61
commit b61ac4d969

View File

@@ -41,32 +41,50 @@ const convertObjectToXml = (
for (const key in obj) { for (const key in obj) {
const value = obj[key]; const value = obj[key];
const keyString = isNaN(Number(key)) ? key : `row-${key}`; const keyString = isNaN(Number(key)) ? key : `row-${key}`;
if (Array.isArray(value)) { // Handle null values
value.forEach((item) => { if (value === null) {
xml += `${getIndentation(options, depth)}<${keyString}>${newline}`;
xml += convertObjectToXml(item, options, depth + 1);
xml += `${getIndentation(options, depth)}</${keyString}>${newline}`;
});
} else if (value === null) {
xml += `${getIndentation( xml += `${getIndentation(
options, options,
depth depth
)}<${keyString}></${keyString}>${newline}`; )}<${keyString}></${keyString}>${newline}`;
} else if (typeof value === 'object') { continue;
}
// Handle arrays
if (Array.isArray(value)) {
value.forEach((item) => {
xml += `${getIndentation(options, depth)}<${keyString}>`;
if (item === null) {
xml += `</${keyString}>${newline}`;
} else if (typeof item === 'object') {
xml += `${newline}${convertObjectToXml(
item,
options,
depth + 1
)}${getIndentation(options, depth)}`;
xml += `</${keyString}>${newline}`;
} else {
xml += `${escapeXml(String(item))}</${keyString}>${newline}`;
}
});
continue;
}
// Handle objects
if (typeof value === 'object') {
xml += `${getIndentation(options, depth)}<${keyString}>${newline}`; xml += `${getIndentation(options, depth)}<${keyString}>${newline}`;
xml += convertObjectToXml(value, options, depth + 1); xml += convertObjectToXml(value, options, depth + 1);
xml += `${getIndentation(options, depth)}</${keyString}>${newline}`; xml += `${getIndentation(options, depth)}</${keyString}>${newline}`;
continue;
}
// All other types are treated the same way // Handle primitive values (string, number, boolean, etc.)
} else {
xml += `${getIndentation(options, depth)}<${keyString}>${escapeXml( xml += `${getIndentation(options, depth)}<${keyString}>${escapeXml(
String(value) String(value)
)}</${keyString}>${newline}`; )}</${keyString}>${newline}`;
} }
}
return depth === 0 ? `${xml}</root>` : xml; return depth === 0 ? `${xml}</root>` : xml;
}; };