【问题标题】:Adding variables to response data call in javascript在javascript中将变量添加到响应数据调用
【发布时间】:2020-05-07 17:30:36
【问题描述】:

是否可以将变量连接到对响应数据的调用,如下所示: res.data.{some_variable}?

我正在使用 axios 调用 api,我得到一个 JSON 响应,为了获得一些特定信息,我必须调用对象的每个键。键都是编号的,“object_1”、“object_2”、“object_3”等等。现在,我目前必须调用它的次数与键的次数一样多,但我想知道是否有更好的方法。

我试过res.data.object_${nr},但没用。

这是我的代码:

const path= "path_to_api";
const object_nr = this.$route.params.nodeID;
axios.get(path)
   .then((res) => {
       this.object_devices = res.data.object_1;
   })
   .catch((error) => {
       console.error(error);
   });

但我希望能够像这样添加object_nrres.data.object_{object_nr}

【问题讨论】:

  • 向我们展示更多代码,以便我们更好地了解您要完成的工作。
  • const path= 'path_to_api'; const object_nr = this.$route.params.nodeID; axios.get(path) .then((res) => { this.object_devices = res.data.object_1; }) .catch((error) => { console.error(error); }); 但我希望能够将“object_nr”放在那里而不是“object_1”、“object_2”等等

标签: javascript json axios concatenation


【解决方案1】:

您可以使用索引语法获取属性:

object['name']

所以你可以建立自己的索引:

const foo = 'bar';
object[`name_${foo}`]

【讨论】:

  • 非常感谢,这解决了我的问题!这样做了:const object_nr = this.$route.params.nodeID; this.object_devices = res.data[`ip${test}_devices`];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
相关资源
最近更新 更多