如何使用Lodash根据货币及目标值返回对象对应顶级键?
利用Lodash实现目标函数
首先定义给定的对象:
const obj = { 'MONEY-OUT': { USD: ['a', 'b', 'c'], EUR: ['d', 'e', 'f'], }, 'MONEY-IN': { USD: ['g', 'h', 'i'], EUR: ['j', 'k', 'l'], }, };
接下来实现满足需求的函数:
const findTopLevelKey = (currency, searchString) => { return _.findKey(obj, (subObj) => { // 检查子对象是否包含指定货币的数组,且数组中存在目标字符串 return _.has(subObj, currency) && _.includes(subObj[currency], searchString); }); };
函数说明
- 使用
_.findKey遍历对象的顶级键,返回第一个符合条件的键 - 通过
_.has确保子对象存在指定的货币属性,避免访问不存在的属性报错 - 用
_.includes判断货币对应的数组是否包含目标搜索字符串
示例调用
// 传入'EUR'和'k',返回'MONEY-IN' console.log(findTopLevelKey('EUR', 'k'));
内容的提问来源于stack exchange,提问作者testerJuan
相关产品推荐
相关产品推荐

