javascript - 将 javascript 对象转换为 HTML
问题描述
所以我需要一个函数来转换类型的 js 对象:
{node: 'X', children: [{node: 'Y'}]}
任何深度的字符串,类似于 html。例如,上面应该转换成类似的东西:
'<div class="X"><div class="Y"></div></div>'
这应该是直观的,因为顺序节点彼此插入的方式与 div 相同。所以这是我到目前为止所拥有的:
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;
}
,
如果子节点数量众多,则问题出在子节点之间。这是我的笑话测试,它失败了
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>');
});
});
帮助表示赞赏!你可以在这里运行测试
解决方案
该问题是由.join()
连接child_nodes
(字符串)和childrn
(数组)时的隐式调用引起的。
只需添加一个.join()
带有空格作为分隔符的显式函数,您的函数就会按预期工作
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)));
推荐阅读
- html - 项目符号点和复选框不适用于降价
- c# - System.Net.Mail.SmtpException:操作已超时
- javascript - 为什么 _.extend 做一个浅拷贝?
- rx-java2 - rxJava2如何根据大小聚合数组
- java - Java 7:发送 TLSv1.2 警报:致命,描述 = handshake_failure mule
- java - 如何从 TextInputLayout 中删除底部填充
- c# - 来自 Api 的数据,显示多个没有数组的对象。是否应该为每个对象单独创建类
- git - 如何使用 IDEA 从 github 克隆一个 maven 项目?
- html - 使用 inline-grid 使中间项目更大
- javascript - Javascript:大括号的可用性