javascript - Lodash - Get Value at Path with Default Values - Stack Overflow

Is there any way to get a value at a path with fallbacks to other paths should they not be defined?var

Is there any way to get a value at a path with fallbacks to other paths should they not be defined?

var object = { a: 1 }

// Try to get d, fallback to e and then a
_.get(object, 'd', _.get(object, 'e', _.get(object, 'a')))

Is there a better method for this that i have missed?

Is there any way to get a value at a path with fallbacks to other paths should they not be defined?

var object = { a: 1 }

// Try to get d, fallback to e and then a
_.get(object, 'd', _.get(object, 'e', _.get(object, 'a')))

Is there a better method for this that i have missed?

Share Improve this question asked Apr 11, 2017 at 22:07 JackJack 1,9411 gold badge19 silver badges33 bronze badges 2
  • Do you need to fallback strictly for undefined properties or can they be false too? If you want to fallback for falsy values too you could do obj.d || obj.e || obj.f otherwise you can do a loop with object.hasOwnProperty and return the value for the first matching key that's defined. – Christopher Commented Apr 11, 2017 at 22:16
  • Preferably only for undefined, but it's acceptable here to fallback for anything falsey. Looking for something more idiomatic than obj.d || obj.e || obj.f . Something like _.pick, but for picking a value, not picking keys. – Jack Commented Apr 11, 2017 at 22:19
Add a ment  | 

2 Answers 2

Reset to default 2

You could make your own helper method for this, perhaps something like this?

function pickValue(obj, keys, defaultValue) {
  var foundKey = keys.find(function(key) { return obj.hasOwnProperty(key); });
  return foundKey ? obj[foundKey] : defaultValue;
}

Usage:

var result = pickValue(obj, ['d', 'e', 'f'], 'default value');

Think I'm going for this but still want to see if anyone es up with something better using lodash.

_.get(object, _.findKey(object, _.rearg(_.partial(_.includes, ['d', 'e', 'f']), 1)))

Update

The above wont work if u want to find the keys for nested paths so back to:

_(object).at('b', 'c', 'd', 'e', 'a').pact().first()

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745288496a4620711.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信