【问题标题】:How to extract data from array instead of Object?如何从数组而不是对象中提取数据?
【发布时间】:2022-01-03 12:07:28
【问题描述】:

如何正确地从数组而不是 [Object] 中提取数据

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

我需要获取值 locationResponseRes.cityName 。 实际输出:

[
  {
    location: { locationId: 1, address: [Object] },
    deliveryOptions: [ [Object] ]
  },
  {
    location: { locationId: 2,},
    cityName: [ [Object] ]
  }
]
{
  "location": {
    "locationId": 1,
    cityName: [ [Object] ]
  }
}

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

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

以及如何到达locationResponseRes.cityName

【问题讨论】:

    标签: javascript arrays reactjs typescript


    【解决方案1】:

    有几种方法可用于控制台嵌套对象。

    最好的方法是使用

    console.log(JSON.stringify(obj, null, 2))
    

    其中 2 是用于缩进的空格数。

    另一种选择是使用

    const util = require('util')
    
    console.log(util.inspect(myObject, {showHidden: false, depth: null}))
    
    // alternative shortcut
    console.log(util.inspect(myObject, false, null, true /* enable colors */))
    

    require('util').inspect.defaultOptions.depth = null
    console.log(obj)
    

    但问题是2级之后的嵌套对象现在被展平了,这可能是复杂对象的问题。

    查看Node.js official documentation

    【讨论】:

    • 如何使用地图?类似的东西 const locationResponseRes = locationResponse; const availableLocation =availableLocationResult.map()?
    • 我认为它也应该与 Array 一起使用。你试过了吗?
    • 不知道怎么正确
    • 代替console.log(obj),用你的数组替换obj。 console.log(array)
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2021-05-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多