考虑对象:
var myObj = {
hugeKey1: 'xxx',
hugeKey2: 'xxx',
hugeKey3: 'xxx',
hugeKey4: 'xxx',
prettyKey1: 'Only one'
};
以下是获取模式为hugeKey
的所有密钥列表的代码:
var filteredKeySet = _.filter(
Object.keys(data),
function (key) {
if (key.match(/hugeKey/i)) {
return true;
}
}
);
只有一个名为PrettyKey1
的键,但最后的数字是动态的 - 也可能是PrettyKey2
。
使用模式匹配找到第一个密钥的最短代码是什么?
看起来像Object.keys(myObj).findFirstMatch(/PrettyKey/i);
答案 0 :(得分:1)
根据您的要求,这可能就是您所需要的:
const firstMatchedKeyNameInObject = Object.keys(myObj).find(keyName => keyName.includes('prettyKey'));
答案 1 :(得分:1)
除了之前的答案,如果您需要经常执行此类操作并且目标对象也在更改,您可以编写以下实用程序功能:
function matchBy(pattern) {
return obj => Object.keys(obj).find(k => k.match(pattern));
}
或
function findBy(pattern) {
return obj => Object.keys(obj).find(k => k.includes(pattern));
}
然后将它们用作:
var match = matchBy(/prettyKey/i);
var find = findBy("prettyKey");
....
console.log(match(myObj));
console.log(find(myObj));
答案 2 :(得分:1)
来自
function callback(elm){
if(elm.match(/prettyKey/i)) return true;
}
Object.keys(myObj).findIndex(callback);
到
Object.keys(myObj).findIndex(key=>key.match(/PrettyKey/i))
或
Object.keys(myObj).findIndex(key=>key.includes('prettyKey'))
答案 3 :(得分:0)
好的,所以在发布后几乎立即找到了答案:
Object.keys(myObj).findIndex(x=>x.match(/PrettyKey/i))
只需要在密钥上使用基于=>
的索引搜索。
想知道是否有更快的方式通过lodash这样做。