[英]Typescript name of key in Object
Suppose we have object like this: 假设我们有这样的对象:
foo = {
"currency": "dollar"
}
Is it possible to check if value of object exists and is equal to dollar? 是否可以检查对象的值是否存在并且等于美元? For example:
例如:
const bar = currency;
So how can we pass the value of bar to foo path? 那么如何将bar的值传递给foo path? Or use any syntax that should work as $bar?
还是使用任何应用作$ bar的语法? I don't want to pass $bar as a path name but a value of bar as a path.
我不想将$ bar作为路径名传递,而将bar的值作为路径传递。
foo.$bar? true: false
in result foo.currency === true or false
Or even is it possible to have another object like: 甚至可能还有另一个对象,例如:
anotherobject.anotherpath.$(getKey(foo))
to get object like anotherobject.anotherpath.currency? 获得像anotherobject.anotherpath.currency这样的对象?
Hope it's clear enough to understand 希望它足够清楚地理解
Objects act a bit like arrays in that you can access values stored in a certain index using the bracket notation - but in this case, using the key or field in place of the numeric index. 对象的行为有点像数组,因为您可以使用方括号表示法访问存储在特定索引中的值-但在这种情况下,可以使用键或字段代替数字索引。
So you can: 所以你可以:
const foo = { "currency": "dollar" };
const bar = "currency"
if (foo[bar] == "dollar") { /* do something */ }
If you want to check if the 'bar' property exists in the foo object, you can also do: 如果要检查foo对象中是否存在'bar'属性,则还可以执行以下操作:
const foo = { "currency": "dollar" };
const bar = "currency"
// will check if foo.bar exists
if (foo.hasOwnProperty(bar)) {/* do something */}
var foo = {
"currency": "dollar"
};
var bar = "currency";
Check if the key exists: 检查密钥是否存在:
if (foo[bar])
Or: 要么:
if (foo.hasOwnProperty(bar))
Check if property has the right value 检查属性值是否正确
if (foo[bar] == "dollar")
You can use Object.values() : 您可以使用Object.values() :
example is below: 示例如下:
var foo = {
"currency": "dollar"
};
var bar = "currency";
console.log(Object.values(foo).indexOf(bar) >= 0); //false
console.log(Object.keys(foo).indexOf(bar) >= 0); //true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.