Home > Software engineering >  Not all data is displayed in an array
Not all data is displayed in an array

Time:11-25

I'm trying to get data via api.

apiClient:

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

Actual output :

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

Expected output(that what i got in Postman) :

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

So, as you can see, that not all data is displayed in an array. Maybe i need to do it via entity[] ?

CodePudding user response:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. so instead of unpacking the first object from an array, just return the array itself.

I've added a small example for you to better understand how destructuring works:

[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]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Bottom line, return locationResponse instead of the locationResponseRes object (that line can be removed)

  • Related