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? Or use any syntax that should work as $bar? I don't want to pass $bar as a path name but a value of bar as a path.
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?
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:
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() :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.