0

A second question about my project "Avatar database". I want to collect all tags from all avatars into one array. Of course the list should not contain duplicates.

For example, I have 3 avatars with the tag "red" and in the array "allTags" - "red" is displayed only once.

Data structure

data() {
  return {
    avatars: [
      {
        name: "Butterfly Blue",
        tags: ["animal", "butterfly", "blue"]
      },
      {
        name: "Butterfly Green",
        tags: ["animal", "butterfly", "green"]
      },
      {
        name: "Deer Shining",
        tags: ["animal", "deer"]
      }
    ]
  }
}

I'm trying to get those tags using a computed property:

allTags() {
  var result = [];
  for (var avatar in this.avatars) {
    for (var tag in avatar.tags) {
      if (!tag in result) {
        result += tag
      }
    }
  }
  return result
}

But... The only output I can see is: [] - an empty array.

I want the computed property allTags to return an array ([]) of all tags from all avatars.

Using the example data above {{ allTags }} should be:

[ "animal", "butterfly", "blue", "green", "deer" ]

1 Answer 1

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/[email protected]/dist/vue.min.js"></script>

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very thank you! One thing... Why for..of instead of for..in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.