How to merge and nest multiple layers of json in node.js

Viewed 14

I have a merge function that successfully fetches entities from a json file that matches an ID and merges them into a single json object.

router.get('/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) );
    console.log(reportFragments)

    const merged = reportFragments.reduce((acc, curr) => {
        const match = entities.filter(ent => ent.fragments.includes(curr.id));

        return [...acc, ({
          id: curr.id,
          title: curr.title,
          reports: curr.reports,
          ...{
            entities: match
          }
        })]
      }, [])
      
    res.render(__dirname + "/report", { report: report, fragments: merged });
});

I would like to merge in id's that are referenced in the entities.json file in linkedEntitiesso entities.json

{
  "id": 1,
  "title": "James Smith",
  "linkedEntities": [2],
  "similarOther": [3],
  "similarThis": [],
  "fragments": [1],
  "attributes": {
    "Date of birth": "24/4/1967"
  }
},
{
  "id": 2,
  "title": "John Smith",
  "linkedEntities": [2],
  "similarOther": [3],
  "similarThis": [],
  "fragments": [1],
  "attributes": {
    "Date of birth": "24/4/1967"
  }
}

Is merged to become:

{
    "id": 1,
    "title": "James Smith",
    "linkedEntities": [{
        "id": 2,
        "title": "John Smith",
        "linkedEntities": [2],
        "similarOther": [3],
        "similarThis": [],
        "fragments": [1],
        "attributes": {
            "Date of birth": "24/4/1967"
        }
    }],
    "similarOther": [3],
    "similarThis": [],
    "fragments": [1],
    "attributes": {
        "Date of birth": "24/4/1967"
    }
}

How would I go about achieving that?

0 Answers
Related