首页 > 解决方案 > 如何从三个 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,我们将idtitle作为来自 json 1 的对象,然后我们original_name从 json 2 和year来自 json 3 的对象获取,我们将拥有:

{
   "id":"265",
   "title":"Battle of Gettysburg",
   "original_name":"United States",
   "year":"1863"
}

笔记

上面的 json 只是示例,实际上它们是三个巨大的列表,我可以(手动)做的就是加入它们以获得单个 json。

标签: javascriptjqueryjson

解决方案


如果您想组合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>


推荐阅读