繁体   English   中英

是对象Ramda中的数组或字符串中的值

[英]Is value in array or string inside object Ramda

这里有点奇怪,我正在解析查询字符串,有时它们作为字符串返回,其他时候作为字符串数组返回(取决于是否存在一个与多个字符串相比)。

我想知道该值是否存在于键下,并且当数据为空或空时它需要工作。

# we have access to both the key and value
const key = 'locations'
const value = 'London'

数据的形状如下:

# does 'London' exist under `locations`?
{
  locations: 'London',
  skills: ['1', '2'],
}

数据的形状也可能如下所示:

{
  locations: ['London', 'Reading'],
  skills: '1',
}

我已经看过使用pathSatisfiespathEqcontains但没有运气。 我似乎对这个值可以包含在字符串或数组中的事实感到困惑。

我会用一个镜头把钥匙转换成一个阵列,如果它不是一个。 然后你可以简单地使用propSatisfies includes

 const toArr = unless(is(Array), of); const check = (key, value) => pipe( over(lensProp(key), toArr), propSatisfies(includes(value), key)); console.log( check('locations', 'London')({locations: ['London', 'Reading']}) ); console.log( check('locations', 'London')({locations: 'London'}) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> <script>const {unless, is, of, pipe, over, lensProp, propSatisfies, includes} = R;</script> 


编辑:实际上这可以简化为includes字符串和数组的工作:

 const check = (key, value) => where({[key]: includes(value)}) console.log( check('locations', 'London')({locations: 'London'}) ); console.log( check('locations', 'London')({locations: ['London', 'Reading']}) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> <script>const {where, includes} = R;</script> 

如注释中所述,使用Array.isArray()来查看属性是否包含数组并使用数组方法(如果有),否则直接比较value

 const key = 'locations', value = 'London', data = { locations: 'London', skills: ['1', '2'], }, data2 = { locations: ['London', 'Reading'], skills: '1', } const hasValue = (data, key, value) => { const testVal = data[key]; return Array.isArray(testVal) ? testVal.includes(value) : testVal === value; } // string version console.log(hasValue(data, key, value)); // array version console.log(hasValue(data2, key, value)) 

这个小功能应该让你到那里。

function hasValue(obj, key, value) {
    if (!obj) return false;
    let prop = obj[key];
    if (!prop) return false;
    if (Array.isArray(prop))
        return prop.indexOf(value) >= 0;
    return prop === value;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM