首页 > 解决方案 > Check if string is in an array of objects VueJS?

问题描述

I have a text field where a user can input the value and then on click of a button push the value inside an array. The value i want to test for is the uniqueID. So let's say if the user inputs multiple values including comma or white spaces and one of them matches the uniqueId in the existing array. Then i get an alert.

I tried using some but that didn't quite work. Not sure what i am doing wrong.

Here is a sample pen

new Vue({
  el: "#app",
  data() {
    return {
      myArray: [{
          title: "Sam",
          age: 36,
          uniqueId: "GHTR435"
        },
        {
          title: "Max",
          age: 44,
          uniqueId: "MLKT432"
        }
      ],
      inputField: "",
      inputArray: []
    };
  },
  methods: {
    createArray() {
      if (this.myArray.some((el) => el.uniqueID === this.inputField)) {
        alert("Heyy!!!!");
      } else {
        this.inputArray.push(this.inputField.trim().replace(/, +/g, ","));
        console.log(this.inputArray);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout justify-center>
        <v-flex xs6>
          <v-text-field solo v-model="inputField"></v-text-field>
          <v-btn @click="createArray">Click Me</v-btn>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</div>

Any help will be appreciated. Thank you.

标签: javascriptarraysvue.js

解决方案


你的情况有误。它应该是

this.myArray.some((el) => el.uniqueId /* <-- "d" instead of "D" */ === this.inputField)

推荐阅读