有没有办法将密钥传递到aa字符串可能匹配对象的多个值的JavaScript数组中?
因此,如果我只有一个钥匙可以匹配,那么类似的东西
var str = "foo";
let [key,val] = Object.entries(obj).find(([key,val]) => val== str);
return key;
会很好地工作。但是,如果值匹配,是否有一种方法可以添加多个键?
给出一个可能与上述字符串匹配的对象的示例:
obj = {
quay: "foo",
key1: "blargh",
yaya: "foo",
idnet: "blat",
blah: "foo",
hahas: "blargh"
}
我要做的就是返回所有“ foo”键(quay
,yaya
和> Blah
)基于上面的匹配var str
。
我确定答案是我忽略的简单的东西。
So, if I have only one key to match, then something like:
var str = "foo";
let [key,val] = Object.entries(obj).find(([key,val]) => val== str);
return key;
would work beautifully. But is there a way to add multiple keys if the value matches?
To give example of an object that might match the above string:
obj = {
quay: "foo",
key1: "blargh",
yaya: "foo",
idnet: "blat",
blah: "foo",
hahas: "blargh"
}
What I want to do is return all of the "foo" keys (quay
, yaya
, and blah
) based on the matching var str
from above.
I'm sure the answer is something simple I'm overlooking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
过滤器
而不是查找
和地图
以删除值。Use
filter
instead offind
andmap
to remove the values.使用
object.keys()
获取一系列键,然后用array.filter()
过滤它们。在过滤器的谓词函数中,使用键 -obj [键]
从对象中获取相关值,并将其与str
进行比较。Use
Object.keys()
to get an array of keys, and filter them withArray.filter()
. In the filter's predicate function take the relevant value from the object using the key -obj[key]
and compare it tostr
.您可以像做所有的条目一样获取所有条目,但是不要使用查找,而是用
str
上的所有条目过滤并将其映射到列表中。像这样:You could get all the entries like you are doing, but instead of using find, filtering all the entries with the value on
str
that you want to find and mapping it to a list. Like this:另一种方法:
Another way: