Return 带下划线的值模糊搜索键
Return key for fuzzy search of value with underscore
我正在尝试 return 给定近似匹配值的键。
这是我的字典数据
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
}
有没有更简单的方法来使用下划线或 vanilla js 来代替循环?基本上,如果输入字符串有来自 "key" 的任何子字符串匹配,那么 return 和 "value".
例子
input: "nova_w2" output: "nov"
input: "nova_2323" output: "nov"
input: "novae" output: "nov"
input: "euro12" output: "eur"
如果你必须检查整个字典,你就不能不循环地做这件事。
但这很简单。遍历字典。如果单词包含键,return 值。
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
};
const lookup = word => {
const match = Object.entries( dict ).find(([ key, value ]) => word.includes( key ));
return match
? match[ 1 ]
: false;
};
console.log( lookup( 'nova_w2' ));
console.log( lookup( 'nova_2323' ));
console.log( lookup( 'novae' ));
console.log( lookup( 'euro12' ));
console.log( lookup( 'thisShouldNotBeFound' ));
我们可以使用 Object.keys()
在对象中搜索正确的键,然后使用 find 我们可以找到匹配的键。
let key = Object.keys(dict).find(key => this.value.includes(key))
这是一个工作示例:
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
}
const input = document.querySelector('input')
input.addEventListener('input', function() {
let key = Object.keys(dict).find(key => this.value.includes(key))
console.log(dict[key])
})
<input type="text">
我正在尝试 return 给定近似匹配值的键。 这是我的字典数据
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
}
有没有更简单的方法来使用下划线或 vanilla js 来代替循环?基本上,如果输入字符串有来自 "key" 的任何子字符串匹配,那么 return 和 "value".
例子
input: "nova_w2" output: "nov"
input: "nova_2323" output: "nov"
input: "novae" output: "nov"
input: "euro12" output: "eur"
如果你必须检查整个字典,你就不能不循环地做这件事。 但这很简单。遍历字典。如果单词包含键,return 值。
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
};
const lookup = word => {
const match = Object.entries( dict ).find(([ key, value ]) => word.includes( key ));
return match
? match[ 1 ]
: false;
};
console.log( lookup( 'nova_w2' ));
console.log( lookup( 'nova_2323' ));
console.log( lookup( 'novae' ));
console.log( lookup( 'euro12' ));
console.log( lookup( 'thisShouldNotBeFound' ));
我们可以使用 Object.keys()
在对象中搜索正确的键,然后使用 find 我们可以找到匹配的键。
let key = Object.keys(dict).find(key => this.value.includes(key))
这是一个工作示例:
const dict = {
"key": "value",
"nova": "nov",
"euro": "eur"
}
const input = document.querySelector('input')
input.addEventListener('input', function() {
let key = Object.keys(dict).find(key => this.value.includes(key))
console.log(dict[key])
})
<input type="text">