如何从对象获取值

时间:2020-09-23 05:15:08

标签: javascript

我在下面有一个物体;

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

我想获取Question0Question1Question2的值。格式为Question[index]。使用循环获取全部内容可能是

有人帮我吗?

1 个答案:

答案 0 :(得分:1)

只需从0到2遍历循环并创建相应的密钥即可。使用此功能,您可以访问所需的值。

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);
}