首页 > 解决方案 > 将 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>');    
  });
}); 

帮助表示赞赏!你可以在这里运行测试

标签: javascriptalgorithm

解决方案


该问题是由.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)));


推荐阅读