find the position of an item within a list

Is it possible to get the index of an object in JavaScript?

For example:

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

I am trying to get the index of software, but when I use indexOf, I receive an error stating that indexOf is not a function. This is because it's a list of objects. Can this be achieved in any other way?

Here is a sample fiddle for you guys to test: https://jsfiddle.net/50wL7mdz/86966/

Thank you in advance

Answer №1

To utilize the index within a v-for loop, you can reference it as (category, index) in categories. Check out this demo on JSFiddle.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

Issue with Firebase V9 addDoc: No indication of success or failure, and data is not being written to the

I am encountering an issue where the authentication related functions are working fine, but I am unable to make any progress with Firestore. Despite no errors or successes being returned by the try-catch block, nothing seems to happen in the Firestore data ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

An issue with three.js involving sprites, the material of sprites, and detecting mouse clicks

Hello there, I appreciate you taking the time to read this. I've been diving into various tutorials on how to click objects using the mouse in three.js. However, none of them mentioned whether it's possible with sprites. To try and work around th ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

The match() function does not seem to be functioning properly on iOS and Android devices, as it consistently returns a

Currently, I have a loop set up to go through a list of names in order to check if the user's search query (stored as variable "s") matches any of the names. This loop functions perfectly on desktops and laptops, but unfortunately, it does not work on ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

Creating an array of objects through checkbox validation in AngularJS

$scope.data = [{ 'id': '1', 'itemName': 'mousepad', 'price': '20' }, { 'id': '2', 'itemName': &apo ...

Tips for ensuring the middle row remains sandwiched between the header and footer rows in Bootstrap

After adding styles for img with max-height:100% and max-width:100%, the display looked fine with just images. However, upon further inspection, I noticed that if the middle row (which can contain one or two columns side by side) has multiple images or an ...

What is the best way to generate a div with a dynamically changing variable as its ID?

Creating a quiz where the user can choose how many questions to answer. A function is used to generate individual question divs based on the user's input. Each question displays a Chinese character, and the user must select the correct translation. ...

Angular js is failing to populate dropdown values

I'm encountering an issue with editing a user object. When clicking the edit button, some values in the form are loading correctly, but three values are not populating even though I'm receiving the data from the service. HTML < ...

Developing MCRYPT_RIJNDAEL_128 from scratch in Node.js

Attempting to replicate the php encryption script below using node.js: $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($size, MCRYPT_RAND); $msg = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, 'MY_KEY_LONG ...

Issue with Pure Javascript FormData upload involving files and data not successfully processing on PHP end

My file upload form follows the standard structure: <form id="attachform" enctype="multipart/form-data" action="/app/upload.php" method="POST" target="attachments"> <!-- MAX_FILE_SIZE must precede the file input field --> <i ...

Is it possible to disable the next and previous buttons in jCarousel?

I am currently using the jCarousel slider from for my website. The slider displays one image at a time, with a total of four images. I want to hide the previous arrow when displaying the first image and hide the next arrow when displaying the fourth image ...

Determine the selected option in the dropdown menu upon loading the page and when clicked

I am working on capturing the value of a drop-down list whenever it is changed or when the page loads. The aim is to display different div elements based on the selected option in the report field - either State or Year. Any assistance with this would be ...

Calculating the angle formed by three vectors in three-dimensional space

According to the solution(s) provided in this post Angle between 3 points in 3d space, there is a JavaScipt function that calculates the angles between three vectors in 3D space. The function calculates the angles as if each vector is a vertex on a surface ...

Is the condition failing to evaluate for all td elements?

I am currently dealing with an HTML table. When I select a checkbox, I aim to compare the values of the cells in each row. This comparison works correctly for the first row, but it does not work for any subsequent rows. HTML Code - <form role="fo ...

Sorry, the server cannot be reached at the moment. Please try again later

Recently delving into Node.js and just getting started on using MongoDB. Currently establishing a connection with my MongoDB Cluster that I have set up. const dbURI = 'mongodb+srv://testuser:<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...