0

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

3
  • 1
    Are you maybe looking for foo[bar]? Like in foo[bar] == "dollar"? Commented Jan 15, 2019 at 21:19
  • @Aioros, mate I don't want to check the value, but if the specific path exists. This way I want to be sure if path foo.$bar exists, where $bar = currency. Commented Jan 15, 2019 at 21:23
  • you can do if (bar in foo && foo[bar] === 'dollar') where bar = 'currency' developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 15, 2019 at 21:29

3 Answers 3

1

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 */}
Sign up to request clarification or add additional context in comments.

2 Comments

As I've mentioned, I don't want to check if value of 'currency' is 'dollar' but I want to check if foo.$bar exists, where $bar = currency :)
the hasOwnProperty function will check if the foo object has the 'currency' field, is that what you needed?
1
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")

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.