英文:
JavaScript - if value exist in array return object key
问题
I got an object of three array ranges (high, medium, low) containing random numbers.
我得到了一个包含随机数字的三个数组范围对象(高、中、低)。
How can i search through all three value arrays and return the object key for the one that matches the search number?
如何在这三个值数组中进行搜索并返回与搜索数字匹配的对象键?
Example:
示例:
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
// returns undefined, should return medium
// 返回 undefined,应该返回 medium
console.log(Object.keys(rangesObj).find(val => search.includes(val)))
英文:
I got an object of three array ranges (high, medium, low) containing random numbers.
How can i search through all three value arrays and return the object key for the one that matches the search number?
Example:
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
// returns *undefined*, should return *medium*
console.log(Object.keys(rangesObj).find(val => search.includes(val)))
答案1
得分: 2
- 使用
rangesObj[key]
来获取与每个特定键对应的数组,然后使用Array#includes
。 - 需要先将
search
转换为数字,以使类型匹配。
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
console.log(Object.keys(rangesObj).find(k => rangesObj[k].includes(+search)));
英文:
- Use
rangesObj[key]
to get the array corresponding to each particular key, then useArray#includes
. search
needs to be converted to a number first so that the types match.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
console.log(Object.keys(rangesObj).find(k => rangesObj[k].includes(+search)));
<!-- end snippet -->
答案2
得分: 1
val
在你的示例中是键,所以你需要使用 rangeObj[key]
来让 include()
完成它的功能。
此外,将 search
转换为数字 (+search
),否则它不会匹配。
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
const res = Object.keys(rangesObj).find(key => rangesObj[key].includes(+search))
console.log(res)
希望这有所帮助。
英文:
val
in your example is the key, so you'll need rangeObj[key]
to let include()
do his thing.
Also, convert search
to number (+search
) otherwise it wont match
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const search = "63";
const rangesObj = {
high: [67, 94, 57],
medium: [43, 89, 63, 12],
low: [27, 41, 77, 99],
};
const res = Object.keys(rangesObj).find(key => rangesObj[key].includes(+search))
console.log(res)
<!-- end snippet -->
答案3
得分: 1
Object.keys(rangesObj).find(x => rangesObj[x].includes(+search))
英文:
Object.keys(rangesObj).find(x => rangesObj[x].includes(+search))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论