반응형
vue.js의 어레이에 항목이 이미 있는지 확인하는 방법
클릭해서 값을 추가할 수 있는 배열이 있는데 값이 이미 배열에 있는지, 아무것도 하지 않는지 확인합니다.indexOf로 시도했지만 매번 같은 결과가 나온다.
this.fields.push(this.field);
this.field = { value: '' };
오브젝트 배열에서는 사용하는 것이 좋습니다.Array.some()
this.users = [{id : 1, name : 'Jonh Doe'},{id : 2, name : 'Mary Jean'}]
if(!this.users.some(data => data.id === 1)){
//don't exists
}else{
//exists because Jonh Doe has id 1
}
출처 : https://www.samanthaming.com/
어레이에 있는지 어떤지를 판단하고 있습니까?value
부동산?만약 그렇다면Array.some()
.
var exists = this.fields.some(function(field) {
return field.value === this.field.value
});
if (!exists) {
this.fields.push(this.field);
}
이것은 상세하고 간단한 해결책일 수 있습니다.
JavaScript 또는 Jquery의 경우
//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
// value exists in array
//write some codes
}
// array with objects
var arr = [
{x:'a', y:'b'},
{x:'p', y:'q'}
];
// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p')
{
return elm; // returns length = 1 (object exists in array)
}
});
// or y:'q' exists in arr
var check = arr.filter(function (elm){
if (elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p' && elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// in all cases
console.log(check.length); // returns 1
if (check.length > 0)
{
// returns true
// object exists in array
//write some codes
}
인뷰
<script>
export default {
data: function () {
return {
arr = [
{x:'a', y:'b'},
{x:'p', y:'q'}
],
}
},
methods: {
// assign this function to any event of any dom
checkObjInArr = function(){
var check = this.arr.filter(function (elm) {
if (elm.x == 'a' && elm.y == 'M') {
return elm;
}
});
console.log(check.length > 0); // returns 1
if (check.length > 0)
{
// returns true
// object exists in array
//write some codes
}
},
},
}
</script>
언급URL : https://stackoverflow.com/questions/41454247/how-to-check-if-item-already-exists-in-array-in-vue-js
반응형
'programing' 카테고리의 다른 글
1 ~ 10의 Java 난수 생성 (0) | 2022.08.19 |
---|---|
발기부전이란 무엇이며 어떻게 사용하는가? (0) | 2022.08.14 |
0과 1 사이의 랜덤 부동 생성 (0) | 2022.08.14 |
라우터 뷰에서 외부 컴포넌트로의 Vuej (0) | 2022.08.14 |
Java에서 패키지를 문서화하는 방법 (0) | 2022.08.14 |