json - 自引用 JSON 对象
问题描述
我有一个来自 API 的 JSON 对象,看起来有点棘手。我需要用其他部分引用对象的部分。有关更多上下文,请参见下文。我需要 InboundLegId 来引用 Legs 对象中的 ID。这里有什么想法吗?
我通过 Fetch 调用这个 API,在 Itineraries 中你会得到一个航班的价格,为了获得关于那个航班的更多细节,你需要通过 Id (outboundLegId/InboundLegId) 引用它的“Leg”。
解决方案
因此,您可以像编辑任何其他普通的旧 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.
});
推荐阅读
- python - Python Pandas - 从列表中读取 JSON
- amazon-web-services - terraform 需要来自私有子网和公共子网的子网 ID 用于 nacl 关联
- pine-script - 系列中缺少正在进行的一周的 rsi 值
- python - 在 pyspark 的数组列中使用 SequenceMatcher
- flutter - Fitness Scope 使 OAuth 同意屏幕卡在 Flutter 中
- ios - 反应本机图像不渲染
- c++ - 构造线程时会发生什么,以及线程是如何执行的
- java - 如何以 yyyy-MM-dd 格式设置日期,然后在 Java 1.8 中以相同格式打印出来?
- flutter - 长按时手势检测器和滑动
- linux - 无法从脚本自动推送提交