How to navigate a JSON hierarchy by building div's of sub-items

时间:2018-06-04 16:56:07

标签: javascript json

I've got a JSON object I'm in the process of building (so I can re-structure if it makes sense). It looks like this:

let topics = {
  "topic" : [{
    name: "Sports",
    id: 1,
    items : [{
      name: "Amateur",
      parent: "Sports",
      items: [
        { id: 1, name: "NHL"},
        { id: 7, name: "Winter Olympics"}
      ],
      },
      {
      parent: "Sports",
      name: "Pro",
      items: [
        { id: 2, name: "IIHF"},
        { id: 3, name: "Timbit Hockey"}
      ],
  },
  "name": "Musicians",
  "id": 2,
  "items": [{...}]

I'm trying to build something that will display the level 1 items inside a div, and when one of them get's clicked on, it will display it's sub-items, and if those sub-items have "items", they can be clicked on to display the next level down.

So you would see "Sports" and "Musicians", if you click on Sports, it creates new div's processed from the Items, so you now see "Pro" and "Amateur". Click on one of those, and you see the sub items and so on.

Eventually I want to make it a swipe-type nav, but for proof of concept I'm good with just clicking.

I put together some loose code like this:

let makeNav = (obj) => {
  let newDiv = document.createElement('div')
  newDiv.innerText = obj.name
  newDiv.dataset.id = obj.id
  newDiv.dataset.name = obj.name
  selector.appendChild(newDiv)
}

And I can handle the first level clicks with a function like this:

let processNode = (filterId, parent = null) => {
  console.log('Called processNode with filter', filterId, parent)
  let currentNode = passionPoints.Passion.filter( o => o.name === filterId)
  currentNode[0].items.forEach(item => {
    makeNav(item)
  })
}

But obviously hardcoding the depth isn't ideal. Any good approach for navigating this kind of data layout?

1 个答案:

答案 0 :(得分:0)

It's good if you use "in" approach to navigate an object

let k;
for (k in obj) {

    /*        k : key
     *   obj[k] : value
     */
}

you can create nesting "for" to make elements and put events on elements in the loops.