简体   繁体   English

如何从数组而不是 Object 中提取数据?

[英]How to extract data from array instead of Object?

How to correctly extract data from array instead of [Object]如何正确地从数组而不是 [Object] 中提取数据

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

runCode运行代码

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

I need to get to values locationResponseRes.cityName.我需要获取值 locationResponseRes.cityName。 Actual output:实际 output:

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

Expected output(that what i got in Postman)预期输出(我在 Postman 中得到的)

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

and how to get to locationResponseRes.cityName ?以及如何到达locationResponseRes.cityName

There are several ways that are used to console nested objects.有几种方法可用于控制台嵌套对象。

The best way to do so, while preserving the pretty print, is to use这样做的最好方法,同时保留漂亮的打印,是使用

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

where 2 is the number of spaces to use for indentation.其中 2 是用于缩进的空格数。

Another option is to use另一种选择是使用

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 */))

or或者

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

but the problem is that the nested objects after level 2 are now flattened, and this might be a problem with complex objects.但问题是 2 级之后的嵌套对象现在被展平了,这可能是复杂对象的问题。

Check out Node.js official documentation查看Node.js 官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM