首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何组合和嵌套相关的JSON对象?

如何组合和嵌套相关的JSON对象?
EN

Stack Overflow用户
提问于 2022-07-28 17:18:11
回答 1查看 37关注 0票数 0

我有两个json文件,我想把它们合并成一个json对象,可以在前端读取。

fragments.json

代码语言:javascript
复制
[
    {
      "id": 2,
      "title": "John Smith is nice",
      "reports": "1,2",
      "entities": 1,
    }
]

entities.json

代码语言:javascript
复制
[
    {
      "id": 1,
      "fragments": 2,
      "name": "John SMITH",
      "dateOfBirth": "4/24/1967",
    }
]

理想的Result.json

我想展示连接到任何给定片段的所有实体。

代码语言:javascript
复制
[
    {
       "id":2,
       "title":"John Smith is nice",
       "reports":"1,2",
       "entities":{
          "id":1,
          "fragments":2,
          "name":"John SMITH",
          "dateOfBirth":"4/24/1967"
       }
    }
 ]

到目前为止,这是我的代码:

代码语言:javascript
复制
router.get('/sprint-3/:prototype/report/:reportId', function (req, res) {

    const slug = +req.params.reportId
    const report = reports.find(({ id }) => id === slug);

    const reportFragments = fragments.filter(({ reports }) => reports.includes(report.id) );

    reportFragments.forEach(fragment => {
        const reportEntities = entities.filter(({ fragments }) => fragments === fragment.id );
        reportFragments.push(reportEntities);
        console.log('New', reportFragments)
    });


    res.render("sprint-3/prototype-1/report", { report: report, fragments: reportFragments });
});

我一直认为.push是这样做的一种方式,但目前它将实体附加到reportFragments的末尾,而不是在每个实体中嵌套。

EN

回答 1

Stack Overflow用户

发布于 2022-07-28 18:10:00

您可以像这样使用减缩。

代码语言:javascript
复制
const reportFragments = [{
  "id": 2,
  "title": "John Smith is nice",
  "reports": "1,2",
  "entities": 1,
}]

const entities = [{
  "id": 1,
  "fragments": 2,
  "name": "John SMITH",
  "dateOfBirth": "4/24/1967",
}]

const merged = reportFragments.reduce((acc, curr) => {
  const match = entities.filter(ent => ent.fragments === curr.id);
  return [...acc, ({
    id: curr.id,
    title: curr.title,
    reports: curr.reports,
    ...{
      entities: match
    }
  })]
}, [])

console.log(merged)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73156819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档