【问题标题】:Not all data is displayed in an array并非所有数据都显示在数组中
【发布时间】:2022-01-03 04:21:55
【问题描述】:

我正在尝试通过 api 获取数据。

api客户端:

export interface apiRequest {
  locations: LocationOptions[];

}
interface FOLocations {
  locationId: number;
}

interface LocationResult {
  location: FOLocations[];
  cityName: string;
}

export const locationCheck = async (
  apiKey: string,
  payload: apiRequest
): Promise<LocationResult[]> => {
  let response = await axios.post<LocationResult[]>(
    `api...`,
    payload
  );
  return response.data;

运行代码:

  const locationPayload : apiRequest = {
      locations:[{ cityName: "London"},{cityName: "New York"},{cityName: "Paris"}],
    };
    const locationResponse = await locationCheck(apiKey,locationPayload);
    const [locationResponseRes] =  locationResponse;
    console.log(locationResponseRes);

实际输出:

{
  "location": {
    "locationId": 1,
    "cityName: "London",
  }
}

预期输出(我在 Postman 中得到的):

[
    {
        "location": {
            "locationId": 1,
            "cityName: "London",
        }
    },
    {
        "location": {
            "locationId": 2,
            "cityName": "New York",
        },    
},
]

因此,如您所见,并非所有数据都显示在数组中。也许我需要通过 entity[] 来做?

【问题讨论】:

  • const [locationResponseRes] = locationResponse; 这使用解构并从响应数组中获取第一个对象,只需使用 ` const locationResponseRes = locationResponse; `

标签: javascript arrays typescript postman


【解决方案1】:

解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解包到不同的变量中。所以不要从数组中解包第一个对象,只需返回数组本身。

我添加了一个小示例,以便您更好地了解解构的工作原理:

[a, b] = [10, 20];

console.log(a); // 10

[first, second] = [10, 20, 30, 40, 50];

console.log(second); // 20

[first, second, ...rest] = [10, 20, 30, 40, 50];

console.log(rest); // [30, 40, 50]

底线,返回locationResponse 而不是locationResponseRes 对象(那行可以去掉)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多