首页 > 解决方案 > 组合来自两个不同 API 的数据并解析响应(节点打字稿)

问题描述

我目前正在使用带有 typescript 的 nodejs 开发 RESTful API 后端,我需要从多个不同的 API 收集信息并解析结果并将解析的信息传递给前端。现在我正在研究一个 API 路由,我从两个不同的外部 API 路由收集信息,我使用 https 从那里收集数据。我以 [object Object],[object Object] 的形式将数据发送到我的 Objecthandler,因为我将第一个 http 调用的响应推送到一个数组中,并将我的第二个 http 响应推送到另一个数组中,然后我将其推送到第三个数组中是来自两个响应的组合数据。

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

我的对象处理程序代码如下所示:

function ObjectHandlerAvainsanat(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;
}
}

但是,我得到的错误是

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

TypeError: Cannot read property 'map' of undefined

http 响应中的实际数据如下所示,我想要结果对象数组中的值:

{
"@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"
}

这里有谁知道我做错了什么?提前感谢所有帮助,Br,Victor

标签: arraystypescriptparsingobject

解决方案


TypeError:无法读取未定义的属性“地图”

e.resultsundefined。无论您显示的结果对象如何,这都是一个事实。

使固定

console.log(e)然后从那里去。


推荐阅读