首页 > 解决方案 > Lodash return key if exists, otherwise return the other key

问题描述

Let's say I want to do something like:

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

I can achieve the same using get(myVar, 'someKey', get(myVar, 'anotherKey')). I was wondering if there is another lodash method that looks cleaner than that?

标签: javascriptlodash

解决方案


No built in function in Lodash allows this (sadly). However, as Alexander Nied said in his answer, you can easily create a custom function for this. I will use Lodash functionality instead of vanilla JavaScript just to demonstrate how it can work:

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 is lazily evaluated, so the sequence is map first path to _.get(item, path) and if it fails returns a unique notFound value. Then if the notFound is discarded the next value would be mapped. This continues until either there is a match or all the members of paths are exhausted and the value is undefined.


推荐阅读