如何合并并嵌套关联JSON对象?代码实现遇阻求助
合并JSON并嵌套关联实体数据
需求说明
我有两个JSON文件,需要合并为一个前端可读取的单个JSON对象,核心是将每个fragment关联的entities嵌套到对应的fragment对象内部。
源文件内容
fragments.json
[ { "id": 2, "title": "John Smith is nice", "reports": "1,2", "entities": 1 } ]
entities.json
[ { "id": 1, "fragments": 2, "name": "John SMITH", "dateOfBirth": "4/24/1967" } ]
期望结果
[ { "id":2, "title":"John Smith is nice", "reports":"1,2", "entities":{ "id":1, "fragments":2, "name":"John SMITH", "dateOfBirth":"4/24/1967" } } ]
现有代码问题
当前代码中使用reportFragments.push(reportEntities)会把实体数组追加到整个reportFragments数组的末尾,而非嵌套到每个fragment对象内部,不符合需求。
修正后的代码
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 => { // 一对一关联场景下,用find直接返回单个实体对象,替代filter返回的数组 const reportEntity = entities.find(({ fragments }) => fragments === fragment.id ); // 将实体对象赋值给当前fragment的entities属性,替换原有的数字ID fragment.entities = reportEntity; }); res.render("sprint-3/prototype-1/report", { report: report, fragments: reportFragments }); });
代码说明
- 替换
filter为find:因为你的数据中fragment和entity是一对一关联,find直接返回匹配的单个实体对象,比返回数组的filter更贴合需求。 - 直接修改fragment内部属性:不再往
reportFragments数组末尾追加元素,而是修改每个fragment对象的entities字段,将原数字ID替换为对应的实体对象,实现嵌套效果。
内容的提问来源于stack exchange,提问作者Tom Wicks
相关产品推荐
相关产品推荐

