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
2 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - Lodash - Get Value at Path with Default Values - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745288496a2651647.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论