How to check values exist in an array of objects in vueJS?
June 11, 2022Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
Today I am going to show you How do you check values exist in an array of objects in VueJS.
This is the common task for a frontend developer to check whether the value exists in an array of objects or not. There can be many other ways but in this tutorial, we are going to use the findIndex()
and find()
methods.
All below tutorials work on javascript, React, React Native, Vue, Node, Deno, typescript, and all javascript frameworks.
Table of Content
- Define users array of object for test
- Array.findIndex() method
- Array.find() method
- Array.includes() method
Let’s start the today’s tutorial How do I check values exist in an array of objects in VueJS?
Define users array of the object for a test
Let’s define the number in data of the FirstComponent.vue
component for testing purposes.
<script>
export default {
name: 'FirstComponent',
data() {
return{
users: [
{
id: 1,
name: "sort"
},{
id: 2,
name: "shortout"
},{
id: 3,
name: "Sortoutcode"
}
],
}
},
}
</script>
Data is used to define properties in a particular component. In a single-file component, data()
is a function that returns a set of properties that have been defined in the function.
we define the users array of objects.
Array.findIndex() method
Javascript provides thefindIndex()
method to find value in the array, and we can also use this method to check whether a value exists or not in an array of objects.
Let’s understand the output through the Example
<template>
<div>SortoutCode</div>
</template>
<script>
export default {
name: 'FirstComponent',
data() {
return{
users: [
{
id: 1,
name: "sort"
},{
id: 2,
name: "shortout"
},{
id: 3,
name: "Sortoutcode"
}
],
}
},
mounted(){
let userIndex = this.users.find(e => e.id == 2);
console.log(userIndex); // 1
if(userIndex >= 0){
console.log("Exist");
} else {
console.log("Not exist");
}
}
}
</script>
javascript findIndex()
method return index of object if value match else it will return -1.
For now, let’s check the output of findIndex() method.
Output
Array.includes() method
Javascript find() method same work as findIndex but it will return a whole object or array value if match else it will return undefined.
<template>
<div>SortoutCode</div>
</template>
<script>
export default {
name: 'FirstComponent',
data() {
return{
users: [
{
id: 1,
name: "sort"
},{
id: 2,
name: "shortout"
},{
id: 3,
name: "Sortoutcode"
}
],
}
},
mounted(){
let userIndex = this.users.find(e => e.id == 2);
console.log(JSON.stringify(userIndex)); // 1
if(userIndex){
console.log("Exist");
} else {
console.log("Not exist");
}
}
}
</script>
For now, let’s check the output of find() method.
Output
All the best 👍.