Transform JSON into editable table

Let’s imagine the data contained in an array of objects (data = [ {..},{..}, .. ]) and pushing each object into a mongo localdb (data.forEach(o => { localdb.insert(o) }))
Take in account that some objects contains subobjects and their content is rendered.

Here are the different cases and their representation :

case 0

{ key: "val" }

case 1
{ key: ["val1", "val2"] }

case 2

{
    key: {
      subkey: "val"
    }
}

case 3

{
    key1: {
      subkey1: "val"
    },
    key2: {
      subkey1: "val",
      subkey2: "val"
    }
}

Thanks for your help

It’s not perfect but it somehow work, with a recursive function and helpers that avoid using nested each loops.

Here is the very simple template, using the below table function.

<template name="simplified">
{{#each entries in data}}
{{{table entries}}}
{{/each}}
</template>
Template.simplified.onCreated(function () {})
Template.simplified.helpers({ data() { return localdb.find({}) } })

Template.registerHelper('table', function recur(o, bool) {
  if (bool == true && o instanceof Object ) {
    let entries = Object.entries(o).map(entry => {
      let key = entry[0]
      let value = entry[1]
      return (
        HTML.TABLE({class: 'tuple-vk'},
           HTML.TD({'class': 'item-k'}, HTML.B(key)),
           HTML.TD({'class': 'item-v'}, (value instanceof Object)? recur(value, true): value )  )
    )
    })
   return entries
  }

  let entries = Object.entries(o).map(entry => {
    let key = entry[0]
    let value = entry[1]
    return (
        HTML.TR({class: 'tuple'},
           HTML.TD({'class': 'item-key'}, HTML.B(key)),
           HTML.TD({'class': 'item-val'}, (value instanceof Object)? recur(value, true): value )  )
    )
  })

  render = HTML.toHTML( HTML.TABLE(entries))
  return render
})

I still need to code the part to update the data from the browser.

1 Like