自引用 JSON 对象

Self Referencing JSON Object

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

我通过 Fetch 调用此 API,在 Itineraries 中您可以获得航班的价格,为了获得有关该航班的更多详细信息,您需要参考它的 'Leg' 通过编号 (outboundLegId/InboundLegId).

因此您可以像编辑任何其他普通旧 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.
});