[英]Check if value exists in object
I have object: 我有对象:
var roles = { roles: [0: { name: 'admin' }, 1: { name: 'user' }] }
How I can check if value user
exists? 如何检查值
user
存在?
I tried do: 我试着做:
console.log(('user' in roles));
But this return false
. 但这返回
false
。 Why? 为什么?
in operator checks for property not for it's values in运算符中检查属性而不是其值
let test = {'a':1,'b':2} console.log('a' in test) console.log(1 in test)
How can i search values 我如何搜索值
Here using some
method of array i am checking whether desired value is in object or not. 在这里,我使用
some
数组方法检查所需值是否在对象中。
var roles = { roles: [{ name: 'admin' },{ name: 'user' }] } let searchValue = (input,searchKey) => { return input.some(( {name} ) => name === searchKey) // } console.log(searchValue(roles.roles, 'user')) console.log(searchValue(roles.roles, 'user not foound'))
With a proper object, you could treat roles.roles
as array and find the value with Array#some
. 使用适当的对象,您可以将
roles.roles
视为数组,并使用Array#some
查找值。
This works for any array like structure with an assignment to an array with Object.assign
. 这适用于任何类似结构的结构,并通过
Object.assign
分配给数组。
function check(name) { return Object.assign([], roles.roles).some(o => o.name === name); } var roles = { roles: { 0: { name: 'admin' }, 1: { name: 'user' } } }; console.log(check('user')); console.log(check('bar'));
By taking an array directly, you coult omit the assignment part. 通过直接获取数组,您可以省略赋值部分。
function check(name) { return roles.roles.some(o => o.name === name); } var roles = { roles: [{ name: 'admin' }, { name: 'user' }] }; console.log(check('user')); console.log(check('bar'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.