HarmonyOS鸿蒙Next中使用Axios请求接口时,如何处理动态键名返回值?

HarmonyOS鸿蒙Next中使用Axios请求接口时,如何处理动态键名返回值? 使用Axios请求接口时,返回值类似于{'id_1':{''},'id_2':{''}}这种数据,其中id_1, id_2会根据接口参数不同获取的值有变化,无法创建类去接收,因为id_x会有无限的可能,我应该怎么样获取的到返回值那?

3 回复

对于不固定的key可以参考demo ,转成Map:

@Component
@Entry
struct Index {
  @State str: string = '{"id_1":{"xxx":"123"},"id_2":{"222":"333"}}'

  build() {
    Text('asadasd').onClick(() => {
      let jsonRecord: Map<string, Object> = new Map(Object.entries(JSON.parse(this.str)))

      jsonRecord.forEach((value, key) => {
        console.log("key:" + key)
        console.log("value:" + value)
      })
    })
  }
}

更多关于HarmonyOS鸿蒙Next中使用Axios请求接口时,如何处理动态键名返回值?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中使用Axios请求接口时,处理动态键名返回值可以通过以下方式实现:

  1. 使用Object.keys()Object.values()方法:通过这两个方法可以获取动态键名和对应的值,然后进行进一步处理。
import axios from 'axios';

axios.get('your-api-endpoint')
  .then(response => {
    const data = response.data;
    const keys = Object.keys(data);
    const values = Object.values(data);

    keys.forEach((key, index) => {
      console.log(`Key: ${key}, Value: ${values[index]}`);
    });
  })
  .catch(error => {
    console.error('Error:', error);
  });
  1. 使用for...in循环:遍历返回的对象,直接处理动态键名和对应的值。
import axios from 'axios';

axios.get('your-api-endpoint')
  .then(response => {
    const data = response.data;

    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        console.log(`Key: ${key}, Value: ${data[key]}`);
      }
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });
  1. 使用TypeScript类型断言:如果知道返回值的结构,可以使用类型断言来明确处理动态键名。
import axios from 'axios';

interface ApiResponse {
  [key: string]: any;
}

axios.get<ApiResponse>('your-api-endpoint')
  .then(response => {
    const data = response.data;

    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        console.log(`Key: ${key}, Value: ${data[key]}`);
      }
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });

以上方法可以有效地处理动态键名返回值。

在HarmonyOS鸿蒙Next中使用Axios请求接口时,若返回值包含动态键名,可以通过JavaScript的for...in循环或Object.keys()方法遍历对象,动态获取键名及其对应的值。例如:

axios.get('your-api-endpoint')
  .then(response => {
    const data = response.data;
    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        console.log(`Key: ${key}, Value: ${data[key]}`);
      }
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });

此方法适用于处理动态键名的数据,确保灵活解析API响应。

回到顶部