0

I'm planning to get the index of an object is it possible?

for example:

categories = {
                '1':{code:'HW', name:'Hardware'},
                '2':{code:'SW', name:'Software'},
                '3':{code:'OS', name:'Office Supplies'},
            }

I want to get the index of software if I use indexOf it gives me an error which is indexOf is not a function because it's a list of objects. Is it possible top begin with?

Here's a sample fiddle for you guys to check: https://jsfiddle.net/50wL7mdz/86966/

thanks in advance

2
  • Your fiddle works perfectly, but I noticed that in the fiddle, categories is an array and not an object. Which is it in your actual case? Commented Jan 3, 2018 at 2:29
  • @CRice in my actual case it's an object. on my fiddle I comment out the categories that has a list of objects.. I already know that indexOf will not work because it is not an array. Commented Jan 3, 2018 at 2:31

1 Answer 1

1

You can access the index in v-for like (category, index) in categories, see the fiddle here.

new Vue({
  el: '#app',
  data () {
    return {
      categories: {
        '1':{code:'HW', name:'Hardware'},
        '2':{code:'SW', name:'Software'},
        '3':{code:'OS', name:'Office Supplies'},
      }      
    }
  },
  methods:{
    alertIndex(index){
      alert(index);
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
 <ul>
  <li v-for="(category, index) in categories">{{category.code}} - {{category.name}}
  <button @click="alertIndex(index)">Alert Index</button>
  </li>
 </ul>
</div>

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

Comments

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.