javascript - Lodash 返回键如果存在,否则返回另一个键

标签 javascript lodash

假设我想做这样的事情:

const result = 'someKey' in myVar
  ? myVar.someKey
  : myVar.anotherKey

我可以使用 get(myVar, 'someKey', get(myVar, 'anotherKey')) 实现同样的效果。我想知道是否还有另一种看起来比这更干净的 lodash 方法?

最佳答案

Lodash 中没有内置函数允许这样做(很遗憾)。然而,作为 Alexander Nied在他的回答中说,你可以很容易地为此创建一个自定义函数。我将使用 Lodash 功能而不是 vanilla JavaScript 来演示它是如何工作的:

function getFirst(item, paths) {
  const notFound = Symbol("not found");
  
  return _(paths)
    .map(path => _.get(item, path, notFound))
    .filter(result => result !== notFound)
    .first();
}

const obj = {
  a: {
    b: {
      c: 42
    }
  },
  x: {
    y: 1
  },
  z: 2
};

console.log(getFirst(obj, ['g']));
console.log(getFirst(obj, ['g', 'h', 'z']));
console.log(getFirst(obj, ['g', 'h', 'a.b.c', 'z']));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

Chaining using Lodash 是惰性求值的,所以序列是将第一个路径映射到 _.get(item, path) ,如果失败则返回一个唯一的 notFound 值。然后,如果 notFound 被丢弃,则将映射下一个值。这一直持续到有匹配项或 paths 的所有成员都用完并且值为 undefined

关于javascript - Lodash 返回键如果存在,否则返回另一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58493122/

相关文章:

javascript - bootstrap 下拉菜单设置显示 :none when collapsed

javascript - jquery onkey左右滑动无法正常工作?

javascript - 第三方 js 脚本可以写 cookies 吗?

javascript - 保护图像免遭从网站下载

javascript - IE 和 Chrome 中的 Div 定位和 css 样式更改

javascript - 合并两个对象并重命名相同的属性

javascript - Lodash/JS - 将 _.find 语句转换为 _.forEach

JavaScript 模板(例如Underscore/Lodash): informative advice

javascript - Lodash union 无法与展开操作符一起使用

javascript - 在 typescript 中将对象传递给 ._map