[Vuejs]-How to collect nested data in Vue.js without duplicates?

1👍

You should use !result.includes(tag) instead of !tag in result, and result.push(tag) instead of result += tag:

allTags() {
  var result = [];
  for (let avatar of this.avatars) {
    for (let tag of avatar.tags) {
      if (!result.includes(tag)) {
        result.push(tag)
      }
    }
  }
  return result
}

Also, I have replaced the use of for..in with for..of, this is the recommended construct.

See demo:

new Vue({
  el: '#app',
  data() {
    return {
      avatars: [{
          name: "Butterfly Blue",
          tags: ["animal", "butterfly", "blue"]
        },
        {
          name: "Butterfly Green",
          tags: ["animal", "butterfly", "green"]
        },
        {
          name: "Deer Shining",
          tags: ["animal", "deer"]
        }
      ]
    }
  },
  computed: {
    allTags() {
      var result = [];
      for (let avatar of this.avatars) {
        for (let tag of avatar.tags) {
          if (!result.includes(tag)) {
            result.push(tag)
          }
        }
      }
      return result
    }
  }
})
<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>

<div id="app">
  <h4>Avatars:</h4>
  <p>{{ avatars }}</p>
  
  <hr>
  <h4>allTags:</h4>
  <p>{{ allTags }}</p>
</div>

Leave a comment