我想在数组中搜索特定值。例如,我有一组用户,我想检查该数组中是否存在特定用户。
我的数组如下:
Array(5)
0:{id: "empty", name: "Choose one..."}
1:{id: "option_1", name: "shilpa"}
2:{id: "option_2", name: "anita"}
3:{id: "option_3", name: "admin"}
4:{id: "option_4", name: "user"}
length:5
__proto__:Array(0)
这里我想检查用户“admin”是否存在于数组中?
我尝试了以下但是它将结果返回为false:
console.log(this.observedByProperties.includes('admin'));
任何人都能提供解决方案吗?
答案 0 :(得分:1)
您可以使用array#some
来迭代数组,使用string#includes
检查单词中是否存在admin
。
const arr = [{id: "empty", name: "Choose one..."}, {id: "option_1", name: "shilpa"},{id: "option_2", name: "anita"},{id: "option_3", name: "admin"},{id: "option_4", name: "user"}],
exist = arr.some(({name}) => name.includes('admin'));
console.log(exist);

答案 1 :(得分:0)
您需要使用Array.find来检查具有特定值的对象是否存在,
\x61
答案 2 :(得分:0)
这是一个generalized function
,array
和value
为parameters
并返回true
或false
const arr = [{id: "option_1", name: "shilpa"},{id: "option_2", name: "anita"},{id: "option_3", name: "admin"},{id: "option_4", name: "user"}]
function containsValue(arr, x) {
return arr.filter(function(elem) { return elem.name == x }).length > 0;
}
console.log(containsValue(arr, 'admin'))
答案 3 :(得分:0)
你可以使用数组的过滤函数。
let arr = [{id: "empty", name: "Choose one..."}, {id: "option_1", name: "shilpa"},{id: "option_2", name: "anita"},{id: "option_3", name: "admin"},{id: "option_4", name: "user"}];
this.findUser(arr,"Admin");
findUser(array, userName) {
return array.filter(user => user.name === userName);
}