0

I have an object below;

  {
     "Question0":"6",
     "Operator0":">",
     "Condition0":"4",
     "LogicalOperator0":"&&",
     "Question1":"8",
     "Operator1":">",
     "Condition1":"4",
     "LogicalOperator1":"||",
     "Question2":"975",
     "Operator2":"===",
     "Condition2":"test",
     "LogicalOperator2":""
  }

I would want to get the values of Question0, Question1 and Question2. That are of the form of Question[index]. Using a loop to get all may be?

Anyone help me out?

2
  • The Question key should hold an array of values. Then you could literally use Question[index]. Commented Sep 23, 2020 at 5:18
  • we do not access properties with an index, we use keys Commented Sep 23, 2020 at 5:35

1 Answer 1

1

Just iterate over loop from 0 to 2 and create corresponding key. Using this you can access the required values.

const a = {
  "Question0": "6",
  "Operator0": ">",
  "Condition0": "4",
  "LogicalOperator0": "&&",
  "Question1": "8",
  "Operator1": ">",
  "Condition1": "4",
  "LogicalOperator1": "||",
  "Question2": "975",
  "Operator2": "===",
  "Condition2": "test",
  "LogicalOperator2": ""
}

for (let i = 0; i <= 2; i++) {
  const key = `Question${i}`;
  const ans = a[key];
  console.log(ans);
}

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, what if you're not sure of the number of indexes hence number of loops?
Do you mean the number of properties of objects can vary ? And i guess we can use LogicalOperator to check it. The LogicalOperator value will be empty string if we don't have more values, Right ?
No worries, I got a way of figuring that out. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.