首页 > 解决方案 > 自引用 JSON 对象

问题描述

我有一个来自 API 的 JSON 对象,看起来有点棘手。我需要用其他部分引用对象的部分。有关更多上下文,请参见下文。我需要 InboundLegId 来引用 Legs 对象中的 ID。这里有什么想法吗?

在此处输入图像描述

我通过 Fetch 调用这个 API,在 Itineraries 中你会得到一个航班的价格,为了获得关于那个航班的更多细节,你需要通过 Id (outboundLegId/InboundLegId) 引用它的“Leg”。

标签: jsonember.jsfetch

解决方案


因此,您可以像编辑任何其他普通的旧 javascript 对象一样编辑 json 响应:

fetch(...).then(json => {
  json.Itineraries.forEach(itinerary => {
    itinerary.InboundLeg = json.Legs.find(leg => leg.Id === itinerary.InboundLegId);
  });

  // you can now access json.Intineraries[0].InboundLeg.Arrival

  // rest of your code using the json here.
});

推荐阅读