Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从嵌套数组中动态递归地呈现列表项?_Javascript_Html_Reactjs - Fatal编程技术网

Javascript 如何从嵌套数组中动态递归地呈现列表项?

Javascript 如何从嵌套数组中动态递归地呈现列表项?,javascript,html,reactjs,Javascript,Html,Reactjs,给定输出,我想动态列出 results = [ { name: 'a1', results: [] }, { name: 'a2', results: [ { name: 'b1', results: [] }, { name: 'b2', results: [ { name: 'c1',

给定输出,我想动态列出
  • results = [
      {
        name: 'a1',
        results: []
      },
      {
        name: 'a2',
        results: [
          {
            name: 'b1',
            results: []
          },
          {
            name: 'b2',
            results: [
              {
                name: 'c1',
              }
            ]
          }
        ]
      },
      {
        name: 'a3',
      }
    ]
    
    这是预期产出

    <li>a1</li>
    <li>a2</li>
    <li>b1</li>
    <li>b2</li>
    <li>c1</li>
    <li>a3</li>
    
  • a1
  • a2
  • b1
  • b2
  • c1
  • a3
  • 我的伪代码,但我认为这是不接近的。。。我想我需要“递归”解决方案来解决这个问题

    input.map((r) => {
      if(r) {
        return renderResult(r);
      } <<< This is not a recursive way...
      return renderResult(r.results.?);
    });
    
    
    input.map((r)=>{
    if(r){
    返回renderResult(r);
    
    }您的解决方案几乎就是这个

    function generate(arr) {
      const items = [];
      arr.forEach( i => {
        items.push(i.name); //Or whatever you want
      });
      return items;
    }
    
    只需引入递归性

    function generate(arr) {
      const items = [];
      arr.forEach( i => {
        items.push(i.name);
    
        if( !!i.results ){
          const subs = generate(i.results);
          subs.forEach( s => items.push(s));
        }
      });
      return items;
    }
    

    这是我对这个问题的看法

    要将li标记动态插入dom,请使用createElement和append

    const结果=[
    {
    名称:“a1”,
    结果:[]
    },
    {
    名称:“a2”,
    结果:[
    {
    名称:‘b1’,
    结果:[]
    },
    {
    名称:“b2”,
    结果:[
    {
    名称:“c1”,
    }
    ]
    }
    ]
    },
    {
    名称:“a3”,
    }
    ]
    const getNames=(列表)=>{
    常量名称=[];
    函数getDeepNames(列表){
    对于(让列表中的obj){
    名称。推送(对象名称);
    if(数组isArray(对象结果)){
    getDeepNames(对象结果);
    }
    }
    返回姓名;
    }
    返回getDeepNames(列表)
    }
    
    console.log(getNames(results))
    如何使用它构建
  • ?如果我们可以避免预处理并动态呈现它,那将非常好。也许你应该至少参与一点自己的工作,你不认为吗?我解决了“难”的部分,递归。现在剩下的就取决于你了。:)