[英]How can you figure out the name of an object if you know what it's property is equal to?
I am working on a JavaScript program that helps you encrypt and decrypt messages. 我正在开发一个JavaScript程序,该程序可以帮助您加密和解密消息。 In order to make it very secure, I am planning on creating an object that contains the properties of id
and text
. 为了使其非常安全,我打算创建一个包含id
和text
属性的对象。 Here is an example object: 这是一个示例对象:
var object1 = {
id: "AE309JKL36784AJBCMDH"
text: "∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚"
}
Let's say I know that text is equal to ∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚
. 假设我知道文本等于∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚
。 How am I able to figure out that the name of the object that has this value for the property of text
is object1
? 如何确定具有text
属性的该值的对象的名称为object1
?
Thank in advance. 预先感谢。
It depends on the scope
, where you declare your var
, so I would rather use this
(which will also work for window
case): 它取决于scope
,在哪里声明var
,所以我宁愿使用this
(这也适用于window
情况):
var object1 = {
id: "AE309JKL36784AJBCMDH",
text: "∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚"
};
console.log(Object.keys(this).find(k => this[k] && this[k].text && this[k].text === '∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚'));
@Dave Newton is absolutely right, this answer will not work for example in this case: @Dave Newton是绝对正确的,例如,在这种情况下,此答案将无效:
(function(){
var object1 = {
id: "AE309JKL36784AJBCMDH",
text: "∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚"
};
console.log(Object.keys(this).find(k => this[k] && this[k].text && this[k].text === '∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚'));
}())
where this
will be calling scope window
this
将在调用范围window
Object.keys(window).find((key) => {
let obj = window[key];
return obj && typeof obj === "object" && obj.text && obj.id && obj.text === "∆∂˙˚∆ƒ˙ø©ˆ´¨¬˚å˙∂©¬˚";
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.