Mohamed Daher
Mohamed Daher

Reputation: 709

Get Object element from a variable

I have an object that i am trying to pull values from according to a certain variable.

Let say i have an object

current = [
goal1 : solve this,
goal2: sleep,]

current.goal1 returns solve this. but what if i have a variable called task that can be either goal1 or goal2 how can i call current.goal1 by using task variable.

current.task returns undefined.

Is there a way to do that?

Upvotes: 0

Views: 46

Answers (2)

sonEtLumiere
sonEtLumiere

Reputation: 4562

I hope this helps. Object syntax: between curly braces {}

let current = {
  task: {
    goal1 : 'solve this',
    goal2: 'sleep'
  }
};

const { task } = current;

console.log(task)

By using Destructured assignment

Upvotes: 0

namar sood
namar sood

Reputation: 1590

You can do something like this.

const current = {
goal1 : "solve this",
goal2: "sleep"};

const task = "goal1";

console.log(current[task]);

This is known as Square brackets property access: object['property']

Upvotes: 2

Related Questions