javascript - 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.
解决方案
你的情况有误。它应该是
this.myArray.some((el) => el.uniqueId /* <-- "d" instead of "D" */ === this.inputField)
推荐阅读
- java - 使用构建器时映射到蛇盒
- c# - CMake C#:add_dependencies 添加对依赖项的引用
- typescript - 我应该如何在打字稿数据构建功能上正确使用 Partial 和 Record Utility 类型?
- elasticsearch - Elasticsearch 7.14 constant_score 有两个过滤器?
- r - R调查包中的多路聚类标准误差
- javascript - 以编程方式触发“点击”事件不服从对象的目标=_空白
- r - 如何在ggplot的回归线图上添加某些圆圈
- reactjs - 如何在已有 Material UI 的项目中使用组件库中的 Material UI?
- python - Azure ML 不创建目录
- react-navigation - 如何在 react-navigation v6 中覆盖全局 RootParamList