Looking for a function to convert a JavaScript object of this type:
{node: 'X', children: [{node: 'Y'}]}
into a string resembling HTML. For instance, the example above should be transformed to something like:
'<div class="X"><div class="Y"></div></div>'
The conversion should maintain the order in which nodes are nested inside each other as divs.
This is what I have so far:
function convertObj(obj){
const html_start = '<div class="';
const html_end = '</div>';
let current_parent = obj;
let child_nodes = '';
if( typeof(current_parent.children) != 'undefined'){
let children = current_parent.children.map(child_node => convertObj(child_node));
child_nodes = child_nodes + children;
}
return html_start + current_parent.node + '">' + child_nodes + html_end;
}
The issue lies in the commas between child nodes when there are multiple of them. Here's my failing jest test:
describe('convertObj', () => {
it('should turn node value into a div with the same name as its class', () => {
expect(convertObj({node: 'A'})).toBe('<div class="A"></div>');
});
it('should insert child nodes into parent node', () => {
expect(convertObj({node: 'A', children:[{node : 'B'}]})).toBe('<div class="A"><div class="B"></div></div>');
expect(convertObj({node: 'A', children:[{node : 'B'}, {node: 'C', children: [{node: 'D'}]}]})).toBe('<div class="A"><div class="B"></div> <div class="C"><div class="D"></div></div></div>');
});
});
Any help would be greatly appreciated! Run tests here