简体   繁体   English

如果知道对象的属性等同于该对象,该如何确定它的名称?

[英]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 . 为了使其非常安全,我打算创建一个包含idtext属性的对象。 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.

相关问题 可以将变量名设置为等于另一个变量的值吗? - Can you set a variable name equal to another variable's value? 如何从一个日期算出一周 - how can you figure out the week from a single date 当您收到消息“对象不支持此属性或方法”时,您如何找到“对象”是什么? - When you get the message “Object doesn't support this property or method”, how do you find out what “Object” is? 如果仅知道属性名称,是否可以通过setter和getter从对象列表中定义属性? - Can you define properties from a list on an object via setters and getters if you only know property names? 您将如何检查一个对象的属性名称是否存在于另一个对象中? - How would you check if property name(s) from one object exist in another? 如何在事先不知道名称的angularjs中设置对象的属性,并确保绑定正常工作? - How to set a property of an object in angularjs of which you don't know the name in advance, and still make sure the bindings work? 您可以转换显示属性吗? 如果没有,什么是最佳解决方案? - Can you transition a display property? If not, what's the best solution? 可以使用数组作为对象的属性值吗? - Can you use an array as an object’s property value? 如何用字符串加变量命名对象的属性? - How do you name a property of an object with a string plus a variable? 如何在Typescript中扩展对象属性的类? - How do you extend the class of an object's property in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM