javascript - 如何从三个 json 中创建一个新的 json?
问题描述
我有 3 个不同的 json,我需要从中推断出一些数据并用它创建一个新的 json。这三个 json 有一个id
共同的标识符,一个唯一的标识符,所以我们可以将其用作匹配,因为它们实际上是三个不同的大 json。
在 json one 上,我们有"id":"265"
,在 2 和 3 上"article_id":"265"
,所以这些可以作为我们循环时的参考点。
我从来没有以这种方式使用过 json,所以我不知道如何处理它。我已将 jQuery 和 JS 作为标签,因为它们是我最了解的。
1
{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
}
2
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
}
3
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}
所以我正在寻找的最终结果是一个完全像这样的单个 json,我们将id
和title
作为来自 json 1 的对象,然后我们original_name
从 json 2 和year
来自 json 3 的对象获取,我们将拥有:
{
"id":"265",
"title":"Battle of Gettysburg",
"original_name":"United States",
"year":"1863"
}
笔记
上面的 json 只是示例,实际上它们是三个巨大的列表,我可以(手动)做的就是加入它们以获得单个 json。
解决方案
如果您想组合n个 JSON 对象,例如对象列表,您可以采用功能方法并利用 reduce + 过滤器。
const data = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
},
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}];
const final = data.reduce((accu, { id, title }, index, array) => {
// Find any related objects
const matches = array.filter(data => data.article_id === id);
if (matches.length) {
// Flatten them for ease of access. Duplicate keys will override.
const flat = matches.reduce((arr, item) => ({ ...arr, ...item }), [])
// Return new object
return accu.concat({
...flat,
id,
title,
});
}
return accu;
}, []);
console.log(final, '<<')
// Witness
document.getElementById('results').innerHTML = JSON.stringify(final);
<div id="results" style="font-family: Courier; font-size 14px; color: #fff; background: #000; padding: 20px; max-width: 80vw;"></div>
推荐阅读
- c# - 以编程方式启用启动应用程序
- postgresql - 更新迁移后序列化种子数据
- c# - 如何在热敏打印机中打印二维码
- python - 我对列表中的字典有疑问
- python - 数据流工作者安装没有 NAT 的 python 库
- python - Traceback(最近一次通话最后一次):AttributeError:__enter__ - SpeechRecognition 错误
- flutter - 如何使用 bottomAppBar 向抽屉添加额外的屏幕
- kotlin - 如何在 Kotlin 中将 hashmap 转换为 csv 文件
- amazon-ec2 - 那是什么 ??Amazon Elastic Block Storage 快照存储
- react-native - 如何在 React Native 中实现 Paystack 支付网关