我有两个json文件,我想把它们合并成一个json对象,可以在前端读取。
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",
}
]理想的Result.json
我想展示连接到任何给定片段的所有实体。
[
{
"id":2,
"title":"John Smith is nice",
"reports":"1,2",
"entities":{
"id":1,
"fragments":2,
"name":"John SMITH",
"dateOfBirth":"4/24/1967"
}
}
]到目前为止,这是我的代码:
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的末尾,而不是在每个实体中嵌套。
发布于 2022-07-28 18:10:00
您可以像这样使用减缩。
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)
https://stackoverflow.com/questions/73156819
复制相似问题