So I need a function that converts a js object of type:
{node: 'X', children: [{node: 'Y'}]}
with any depth into a string that is similar to html. For example the above should be converted into something like:
'<div class="X"><div class="Y"></div></div>'
This should be intuitive in a way that the order nodes are inserted into each other is same divs are. So here is what I have this far:
function convertObj(obj){ const html_start = '<div class="'; const html_end = '</div>'; let current_parent = obj; let child_nodes = ''; console.log(current_parent, current_parent.children) if( typeof( current_parent.children)!= 'undefined'){ let childrn = current_parent.children.map(child_node => convertObj(child_node) ) child_nodes = child_nodes + childrn } return html_start+current_parent.node+'">'+child_nodes+html_end; }
The problem is ,
between child nodes if they are multiple in number. And here is my jest test, which is failing
describe('convertObj', () => {
it('should turn node value to a div with class of the same name', () => {
expect(convertObj({node: 'A'})).toBe('<div class="A"></div>');
});
it('should incert nodes in children to 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>');
});
});
Help appreciated! You can run tests here
Using some more ES6 syntactic sugar like object destructuring and a template literal , you can make a very simple recursive implementation:
const convertObj = ({ node, children = [] }) => `<div class="${node}">${children.map(convertObj).join(' ')}</div>` const tree = {node: 'A', children:[{node : 'B'}, {node: 'C', children: [{node: 'D'}]}]} console.log(convertObj(tree))
The problem is caused by the implicit call of .join()
when concatenating child_nodes
(a string) and childrn
(an array).
Just add an explicit .join()
with a space as separator and your function works as expected
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 childrn = current_parent.children.map(child_node => convertObj(child_node) ) child_nodes = child_nodes + childrn.join(" "); } return html_start+current_parent.node+'">'+child_nodes+html_end; } [{node: 'A', children:[{node : 'B'}]}, {node: 'A', children:[{node : 'B'}, {node: 'C', children: [{node: 'D'}]}]}] .forEach(test => console.log(convertObj(test)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.