Discovering an array element within another array element in vue - A step-by-step guide

Hi there, I'm currently working on creating a wishlist feature using local storage. The idea is that when the user clicks on the "add to wishlist" button, the item should be added to local storage and then display a "remove from wishlist" option. I attempted to achieve this using ES6's filter and find functions, but I think I may have made a mistake somewhere in my code. You can find the code at this link. Any assistance would be greatly appreciated. Thank you!

https://codesandbox.io/s/wishlist-ouuyw?file=/src/App.vue

<template>
  <div id="app">
  <h2>Total Selected: {{selectedEntries.length}}</h2>
    <div v-for="entry in entries" :key="entry.id">
      <div class="content-wrap">
      
        <h3>{{entry.title}}</h3>
        <button v-if="!checkExists" @click="addToWishlist(entry.id)">Add Wishlist</button>
        <button v-else @click="removeToWishlist(entry.id)">Remove Wishlist</button>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "App",
  data(){
    return{
      entries: [
        {
          title: 'entry one',
          id: 1
        },
        {
          title: 'entry two',
          id: 2
        },
        {
          title: 'entry three',
          id: 3
        },
        {
          title: 'entry four',
          id: 4
        },
        {
          title: 'entry five',
          id: 5
        },
      ],
      selectedEntries: JSON.parse(window.localStorage.getItem("wishlistItems")) || []
    }
  },
  computed:{
    checkExists(){
      return this.entries.filter(entryItem => {
         this.selectedEntries.find(selectedId => {
           return entryItem.id === selectedId.id
         })
      })
    }
  },
  methods:{
    addToWishlist(entryId){
      this.selectedEntries.push({ id: entryId });
      window.localStorage.setItem("wishlistItems", JSON.stringify(this.selectedEntries));
      console.log("Clicked>>>", this.selectedEntries)
    }
  }
};
</script>

<style scoped>
.content-wrap{
  display: flex;
  border: 1px solid;
  margin: 5px;
  padding: 5px;
  align-items: center;
}
.content-wrap h3{
  text-transform: capitalize;
  width: 30%;
}
.content-wrap button{
  border: none;
  padding: 10px 20px;
  height: 30px;
  background-color: #1d9a61;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  line-height: .7
}
</style>



Answer №1

One approach is to create a method that checks for the object's presence in the selected objects array and displays the relevant buttons accordingly. It seems unclear why you are adamant about keeping it strictly as a computed property. Computed properties are generally not used for dynamically computing array element values on the go. A computed property method does not accept arguments directly, making it impossible. They are typically utilized for single values defined within the data property. Refer to their official documentation for more details.

If you still prefer utilizing a computed property exclusively, then you will need to set up a computed property to retrieve the matching items and subsequently implement another method that accepts this array of matching items along with the current entry.id, returning a boolean. However, this might not be the most optimal solution. A better approach would involve having it as a method that takes the present entry.id argument, illustrated below.

.

<template>
  <div id="app">
    <h2>Total Selected: {{selectedEntries.length}}</h2>
    <div v-for="entry in entries" :key="entry.id">
      <div class="content-wrap">
      
        <h3>{{entry.title}}</h3>
        <button v-if="!checkExists(entry.id)" @click="addToWishlist(entry.id)">Add Wishlist</button>
        <button v-else @click="removeToWishlist(entry.id)">Remove Wishlist</button>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "App",
  data(){
    return{
      entries: [
        {
          title: 'entry one',
          id: 1
        },
        {
          title: 'entry two',
          id: 2
        },
        {
          title: 'entry three',
          id: 3
        },
        {
          title: 'entry four',
          id: 4
        },
        {
          title: 'entry five',
          id: 5
        },
      ],
      // selectedEntries: JSON.parse(window.localStorage.getItem("wishlistItems")) || [],
      selectedEntries: [{
          title: 'entry one',
          id: 1
        },
        {
          title: 'entry two',
          id: 2
        }],
    }
  },
  methods:{
    addToWishlist(entryId){
      this.selectedEntries.push({ id: entryId });
      window.localStorage.setItem("wishlistItems", JSON.stringify(this.selectedEntries));
      console.log("Clicked>>>", this.selectedEntries)
    },

    checkExists(entryId){
      return this.selectedEntries.find(item => item.id === entryId);
    }
  }
};
</script>

<style scoped>
.content-wrap{
  display: flex;
  border: 1px solid;
  margin: 5px;
  padding: 5px;
  align-items: center;
}
.content-wrap h3{
  text-transform: capitalize;
  width: 30%;
}
.content-wrap button{
  border: none;
  padding: 10px 20px;
  height: 30px;
  background-color: #1d9a61;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  line-height: .7
}
</style>

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

Troubleshooting Django user login Ajax problem with Bootstrap 3.x modal

After submitting the modal form, an AJAX request is made to pass the username and password to a view and retrieve JSON information to update the form. I have confirmed that the JsonResponse(rsdic) has been executed on the server side and the client receive ...

Determine who the creator of the clicked div is

I'm sorry if my explanation is a bit difficult to comprehend. Here is the code snippet in question: names.push(newName); var strName = newName; var newName = document.createElement('p') newName.setAttribute('id', newName); documen ...

How to assign a specific class to a list item in AngularJS based on its attribute value

Having some difficulties with this code: .directive('mydirective', function() { return { template: '<ul>\ <li priority="500"><a href="#"><i></i>Inbox</a></li>\ ...

Troubleshooting problem with Snapjs Drawer and navigating through scrolling content

Currently, I am utilizing Snap JS to implement a drawer on the left with content displayed on the right. Despite this setup, I am encountering an issue where scrolling is still enabled for the content on the left when the drawer is open. I am seeking guid ...

When an AJAX request is made, it can either return an array or a single object, potentially leading to

My proficiency in Javascript is definitely lacking, and I've only just begun to understand it. I have set up an AJAX call to an API using the GET method. The JSON data returned by the API is pretty standard. If I don't include an ID, I receive ...

Error: Attempting to import statement outside of module when calling JavaScript from Python (Dash)

I am attempting to incorporate a three.js example from the fireship-io YouTube channel to create an animated background on my Python dash application based on user scrolling. The JavaScript script continuously calls a function to update object rotation and ...

How can we use vanilla JavaScript to implement an image zoom effect on mouse movement?

I'm attempting to implement an onmousemove event within an image that displays a zoomed image on the right side. Issue: When I move my mouse inside the image, the black box and zoomed image flicker. The zoomed image does not align correctly in the b ...

The attempt to create the module Application was unsuccessful because of an error stating that the module 'Application' is not accessible

While attempting to utilize fiddle from http://jsfiddle.net/animaxf/uXbn6/4779/, I encountered an issue. When forking the fiddle, it functions correctly. However, when copying and creating a new application (as seen at: http://jsfiddle.net/rishi007bansod/a ...

Python Selenium Tutorial: Selecting an Option from a Dropdown Menu

I need to automate the process of updating the page located at using Python-Selenium. Specifically, I want to simulate clicking on 'Choose an organism -> Homo sapiens', and then clicking on 'Update'. Can someone guide me on how to ...

How can we update the state in Vuex after a certain delay when the snackbar automatically closes?

Working with a Snackbar component in Vue, I utilized Vuetify components to create the snackbar and then imported it into another component. While sending props from the parent to the child snackbar component, an error occurred when the snackbar automatical ...

Performing real-time calculations for standard deviation

I am working with a set of HTML input fields labeled "textfield". I would like to calculate the standard deviation dynamically and display it in another HTML input field. Here is the JavaScript code I am using for the calculation: <script type=&quo ...

Delving into XFN data parsing using Jquery, part two

I need some assistance with correctly parsing the REL attribute on A tags. I have already figured out how to match most XFN values, but there are two that I'm struggling with: "co-worker" and "co-resident". The hyphen seems to be causing an issue with ...

The three.js object is not displaying its shadow as expected

I am relatively new to Three JS and encountering some difficulties with my code. The main issue I'm facing is the inability to achieve proper shadows for all the objects I've integrated. You can see the problem in the following image: https://i. ...

JavaScript nested arrays not functioning with .map()

I've encountered a problem while using the .map function in JavaScript to extract a nested array from an API response. Here is the JSON: [ { "id": 3787, "title": "Dummy title!", "start_time": "2020-04-25T16:54:00.000Z", ...

Error encountered while establishing connection with MongoClient

My server is returning the following error message: MongoClient.connect('mongodb://<'yoda'>:<'yoda69'>@ds235778.mlab.com:35778/satr-wars-quotes', (err, client) => { ^^^^^^^^^^^^^ SyntaxError ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Transferring files via Bluetooth on PhoneGap

As someone new to phonegap, I'm interested in transferring text files from one device to another using Bluetooth within the platform. I've looked at several examples but haven't found a solution yet. I've come across some examples that ...

Is it possible to store a class in a variable and then use that variable to target a specific element?

I am working with the following structure: HTML <ul> <li class="modern"> <button>Ex 1</button> <li> <li class="classic"> <button>Ex 2</button> </li> <ul> <path class="modern"&g ...

Gap positioning at the upper part of the listing area

After finding a design on a website that caught my eye, I decided to make some alterations to fit my needs. The original demo had a vertical layout but I wanted the elements side by side. To achieve this, I created a table with two columns and 100% width. ...