admin管理员组

文章数量:1418371

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

本文标签: javascriptLodashGet Value at Path with Default ValuesStack Overflow