【问题标题】:Is value in array or string inside object Ramda是对象 Ramda 内的数组或字符串中的值
【发布时间】:2019-03-28 06:47:48
【问题描述】:

这里有点奇怪,我正在解析查询字符串,有时它们以字符串的形式返回,有时以字符串数组的形式返回(取决于是否有一个与多个)。

想知道key下是否存在value,需要在数据为空或null的情况下工作。

# 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,但没有运气。我似乎对值可以包含在字符串或数组中的事实感到困惑。

【问题讨论】:

  • Array.isArray(locations) 如果是数组则返回 true,如果不是则返回 false

标签: javascript ramda.js


【解决方案1】:

如果它还不是一个,我会使用镜头将键转换为一个阵列。然后您可以简单地将propSatisfiesincludes 一起使用:

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>

【讨论】:

  • 简化方法的一个潜在问题:check('locations', 'York')({locations: 'New York'}) //=&gt; true
  • 天哪!感谢@ScottSauyet 指出这一点。出于好奇,您认为这可能是lift 的用例吗?
  • 我不知道怎么做。你有什么想法吗?
【解决方案2】:

如cmets中所说,使用Array.isArray()查看属性是否包含数组,如果包含则使用数组方法,否则直接比较值

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))

【讨论】:

    【解决方案3】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多