Merging information from separate APIs and analyzing the output (using typescript)

Currently, I am developing a RESTful API backend using nodejs with typescript. My task involves extracting information from multiple APIs, parsing the results, and then forwarding the parsed data to the frontend. At present, I am focused on an API route where I gather data from two different external API routes using https. The data is then passed to an ObjectHandler in the format [object Object],[object Object]. This structure comes about because I collect responses from my first http call into one array, responses from my second http call into another array, and then push both arrays onto a third array for combined data.

const first: object [] = [
];
const second: object [] = [
];
const combined: object [] = [
];

The code for my object handler is as follows:

function ObjectHandlerKeywords(obj: any): object[] {
const keywords: object [] = [
];
if (obj instanceof Array) {
obj.forEach((e: any) => {
const results = e.results.map((x: any) => x);
const vals = {
localname: results.localname,
prefLabel: results.prefLabel,
altLabel: results.altLabel,
};
keywords.push(vals);
});
return keywords;
}
}

However, I encounter the error message:

const results = e.results.map((x) => x);
^

TypeError: Cannot read property 'map' of undefined

The sample http response data looks like this, and I aim to extract values from within the "results" object array:

{
"@context": {
"skos": "http://www.w3.org/2004/02/skos/core#",
"isothes": "http://purl.org/iso25964/skos-thes#",
"onki": "http://schema.onki.fi/onki#",
"uri": "@id",
"type": "@type",
"results": {
"@id": "onki:results",
"@container": "@list"
},
"prefLabel": "skos:prefLabel",
"altLabel": "skos:altLabel",
"hiddenLabel": "skos:hiddenLabel",
"@language": "FI"
},
"uri": "",
"results": [
{
"uri": "http://www.yso.fi/onto/yso/p22020",
"type": [
"skos:Concept",
"http://www.yso.fi/onto/yso-meta/Concept"
],
"localname": "p22020",
"prefLabel": "pyydystä ja päästä -kalastus",
"lang": "fi",
"altLabel": "catch and release -kalastus",
"vocab": "yso"
},
{
"uri": "http://www.yso.fi/onto/yso/p22337",
"type": [
"skos:Concept",
"http://www.yso.fi/onto/yso-meta/Concept"
],
"localname": "p22337",
"prefLabel": "CATCH-22",
"lang": "fi",
"vocab": "yso"
}

If anyone has insights into what I might be doing incorrectly, your assistance would be greatly appreciated. Best regards, Victor

Answer №1

Oops! Unable to access the 'map' property of an undefined value

e.results is currently undefined. This remains true regardless of the specific results being displayed.

Solution

Start by executing console.log(e) and proceed accordingly.

Answer №2

(assuming x represents your HTTP response)

After analyzing the HTTP response you provided, it seems that x is a JSON object. To work with this JSON object, you can utilize the following code snippet:

let jsonData = JSON.parse(x);

Subsequently, you can access the results by using the following code:

jsonData.results.map((item: any) => item);

I trust this explanation proves to be beneficial...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulty obtaining return value from asynchronous function, await behaving inconsistently in Vue API Service

I am in the process of developing a new service to interact with my API. I am not very familiar with async/await, but I have encountered a puzzling issue that doesn't seem to align with what I've read in the documentation. When attempting to use ...

Angular 16 HttpClient post request with asynchronous action

Here I am working on integrating JWT in Angular with a .Net Core API. When I start my Angular server and launch the application, I encounter the following scenarios: Attempting with correct credentials initially fails, but retrying allows it to work. Tryi ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

Objective C: Eliminating existing UI components

My application is generating a brick every second. When the user taps on a brick, it should disappear. However, I'm facing an issue where tapping on an older brick removes the most recent one instead of the intended one, making it impossible to remove ...

Updating a variable in Nuxt 3 using vue.js

Recently, I started experimenting with Nuxt 3 and Vue 3. All I want is a simple value change when clicking on my div tag. <a id="change" @click="changeValue()">{{value}}</a> <script lang="ts" setup> let val ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link. I am looking to implement a feature where the map comp ...

Tips for streamlining IF statements with multiple conditions

When looking at various code samples, I often see something like this: if(X == x && A == a){ } else if (X == y && A == b){ } else if (X == z && A == c){ } else if (X == zz && A == d){ } Alternatively, there are conditions ...

Utilizing a column's value as an array index in SAS

How can I subset a dataset based on the value of a specific column out of multiple columns? For example, let's say I want to extract rows from the dataset where the value in age is greater than 50. However, I have 10 different age columns labeled as ...

Steps for converting an array of objects to a different array of objects in TypeScript

Is there a way to transform an array of objects into another array of objects in TypeScript? a : [ {bcdbcd : 1, abcabc : "value1"}, {bcdbcd : 2, abcabc : "value2"}, {bcdbcd : 3, abcabc : "value3"} ] a : [ {label: 1, ...

Tips for declaring an immutable object parameter in a Typescript function

Can we prevent an object parameter from being modified in typescript, for example: interface MyType { prop1: number } function myMethod(param: readonly MyType) { // How can we make TypeScript give an error here: param.prop1 = 2 } ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...

The error encountered is: "todos.map is not a function."

I am currently developing a task management application using React, Redux, and TypeScript with hooks. While the code compiles without any errors, I am facing an issue where the app fails to run in the browser. The specific error message states: TypeEr ...

connecting elements within an array in rails

I have two arrays of items and I need to find the total number of matches between them. For instance, given the following arrays: 1 -- House, Dog, Cat, Car 2 -- Cat, Book, Box, Car The result should be 2. Any suggestions? Thank you! EDIT/ Essentially ...

Error encountered when packaging WebAssembly using Rollup

When I use wasm-pack to compile some rust code into webassembly, specifically with the option --target browser (which is the default), these are the files that I see in typescript/deps/ed25519xp: ed25519xp_bg.wasm ed25519xp_bg.d.ts ed25519xp.d.ts ed25519 ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...