[Vuejs]-Vuejs Embedded JSON

0👍

As mentioned in the comments after grouping the array by id you can iterate through it and render your data with two v-fors:

  • 1st loop to get the groups
  • 2nd loop to render the ingredients

Lodash is not required. But it simplifies your code and it’s better tested then self coded. Anyway I’ve added a basic grouping method that is doing the grouping. I would use own grouping method if it is the only part of your app that requires lodash.

Please have a look at the demo below or this fiddle.

//
const jsonData = [{
    "id": 1,
    "bottleID": 1,
    "recipename": "test 1",
    "bottlesize": 60,
    "date": 1,
    "flavorslist": 1,
    "note": "none",
    "flavorid": 3,
    "NAME": "tpa lime",
    "drops": 5,
    "recepeid": 1
  },

  {
    "id": 1,
    "bottleID": 1,
    "recipename": "test 1",
    "bottlesize": 60,
    "date": 1,
    "flavorslist": 1,
    "note": "none",
    "flavorid": 4,
    "NAME": "tpa prome",
    "drops": 1,
    "recepeid": 1
  }
]

new Vue({
  el: '#app',
  data() {
    let groupedJson = this.groupBy(jsonData, (obj) => obj.id) // _.groupBy(jsonData, (obj) => obj.id)
    console.log('grouped by id', JSON.parse(JSON.stringify(groupedJson)))
    return {
      json: groupedJson
    }
  },
  methods: {
    groupBy(data, iterator) {
      let result = {}
      for (let i = 0; i < data.length; i++) {
        let id = iterator(data[i])
        if (!result[id]) result[id] = []
        result[id].push(Object.assign({}, data[i]))
      }
      return result
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app" v-cloak>
  <p>Original data</p>
  <ul>
    <li v-for="(recipes, id) in json">
      {{json[id][0].recipename}}
      <ul>
        <li v-for="recipe in recipes">
          {{recipe.NAME}} - {{recipe.drops}}
        </li>
      </ul>
    </li>
  </ul>
</div>
<div>
  <p>It should be</p>
  <ul>
    <li>test 1</li>
    <li> tpa lime - 5</li>
    <li>tpa prome - 1</li>
  </ul>
</div>

Leave a comment