![](/img/trans.png)
[英]Pointfree Join Array to String, by key in object, in 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',
}
我已經看過使用pathSatisfies
, pathEq
和contains
但沒有運氣。 我似乎對這個值可以包含在字符串或數組中的事實感到困惑。
我會用一個鏡頭把鑰匙轉換成一個陣列,如果它不是一個。 然后你可以簡單地使用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.