Add item to the array if doesn’t exist in Vue.js/ES6

in Code Write a comment

Learn how to add an element to an array if it doesn’t exist JavaScript/Vue.js/ES6.

In this example, there’s an array of objects.

items: [
  { id: 1, text: "Item 1" },
  { id: 2, text: "Item 2" },
  { id: 3, text: "Item 3" }
]

Our task is to add a new item “Item 4” with an id 4 to the array of items.

Vue.js

new Vue({
  el: "#app",
  data: {
    items: [
      { id: 1, text: "Item 1" },
      { id: 2, text: "Item 2" },
      { id: 3, text: "Item 3" }
    ],
    exists: null
  },
  methods: {
    addItem () {
      this.checkIfExists(4)
      if (!this.exists) {
      	this.items.push({'id': 4, 'text': 'Item 4' })
      }
    },
    checkIfExists(itemId) {
      this.exists = this.items.some((item) => {
      	return item.id === itemId
      })
    }
  }
})

HTML

<div id="app">
  <h2>Add item to array:></h2>
  <ul v-if="items.length > 0">
    <li v-for="item in items" :key="item.id">{{ item.text }}</li>
  </ul>
  <p><a href="#" @click.prevent="addItem()">Add new item</a></p>
</div>

There’s a “Add new item” button that’s linked to the addItem() method. This method first calls checkIfExists() method to see if the array of items already contain an item with id = 4.


Hi, I'm Renat 👋

 


If it doesn’t exist, addItem() method proceeds by pushing a new item to the array.

I came up with this solution a long time ago, it’s not elegant. If you know a shorter and cleaner way to add an item to an array and check if it already contains this item – please let me know.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-add-to-array

PS: Make sure you check other Vue.js tutorials, e.g. how to create an array of numbers in JavaScript or generate an array of years in JavaScript.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

2 Comments