[Vuejs]-Recursively walk through an array/object with render functions with javascript

0πŸ‘

βœ…

What about this:

renderFunction(h, arr) {
  return renderStructure(this.test, h)
}

// outside of your App object
function rendeStructure(test, h){
  return h('div', { class: 'link'}, test.map(t => {
    return h('div', {class: 'info'}, [t.name, renderStructure(t.links, h)]);
  }))
}

This does assume there are no cycles in your data.

0πŸ‘

You have an erorr in your code see below I’m calling arr.map you were calling this.test.map

    renderFunction(h, arr) {
      return h('div', { class: 'link'}, arr.map(t => {
        return h('div', t.name);
    }

0πŸ‘

Lazy way, should be correct :

function recurse(obj){
   var html = ['<div class="info"></div>'];
   html.push('<div class="link">')
   if(!!obj.link) html.push(recurse(obj.link[0]));
   html.push('</div>')
   return html.join('')
}

document.getElementsByClassName('item')[0].innerHtml = recurse(obj[0]);

0πŸ‘

You could do this, if you just want the values:

function getVals(mixed){
  var r = [];
  function rec(mixed){
    var a;
    if(mixed instanceof Array){
      for(var i=0,l=mixed.length; i<l; i++){
        a = mixed[i];
        if(typeof a === 'object' && a !== null){
          return rec(a);
        }
        else{
          r.push(a);
        }
      }
    }
    else if(typeof mixed === 'object' && mixed !== null){
      for(var i in mixed){
        a = mixed[i];
        if(typeof a === 'object' && a !== null){
          return rec(a);
        }
        else{
          r.push(a);
        }
      }
    }
    else{
      r.push(mixed);
    }
    return r;
  }
  return rec(mixed);
}
var obj = {
  el: '#app',
  data: {
    test: [{
      name: 'parent',
      link: [{
        name: 'child1',
        link: [{
          name: 'child2',
          deepObj: {
            deepProp:'Number 7 test',
            num:7,
            deeperArray:[true, false, 'test', 'in', 'here', 1]
          }
        }]
      }]
    },
    {
      name: 'parent2'
    }]
  }
}
var vals = getVals(obj);
// getVals returns an Array, hence the .join()
console.log(vals.join(', ')); console.log(vals);

Leave a comment