Home > Back-end >  nest items in JSON based on value?
nest items in JSON based on value?

Time:01-29

Trying to get my head around this one.. Incoming data looks like:

[
    {
        "value": {
            "label": "MZ Algal bloom",
            "type": "case",
            "incident": { 
                "name": "Algal bloom"
            },
            "personName": "Lionel Carter"
        }
    },
    {
        "value": {
            "label": "BW Algal bloom",
            "type": "case",
            "incident": { 
                "name": "Algal bloom"
            },
            "personName": "Jerome Yost"
        }
    },
    {
        "value": {
            "label": "Detergent",
            "type": "case",
            "incident": null,
            "personName": "Jerald Legros"
        }
    }
]

I would like to transform this into

[
    {
        "label": "Algal bloom",
        "children": [ 
            { "label": "Lionel Carter", "type": "case"},
            { "label": "Jerome Yost", "type": "case" }]
    },
    { "label": "Detergent", "type": "case" }
]

Basically, the rule is that if incident is not NULL then the incident name becomes the parent and the children hold the personName - otherwise we simply pass through the label and type. I can walk the array and switch out the label with the incident name, but I'm not sure how to group up the incidents..

CodePudding user response:

It's basic grouping with an exception for elements without incident. You can group the elements without incident in a separate group:

const data = [{"value": {"label": "MZ Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Lionel Carter"}},{"value": {"label": "BW Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Jerome Yost"}},{"value": {"label": "Detergent","type": "case","incident": null,"personName": "Jerald Legros"}}];

function group(data) {
  const result = data.reduce((acc, { value }) => {
    if (!value.incident) {
      acc.ungrouped.push({ label: value.label, type: value.type });
    } else {
      if (!acc.groups[value.incident.name]) acc.groups[value.incident.name] = { label: value.incident.name, children: [] };
      acc.groups[value.incident.name].children.push({ label: value.personName, type: value.type });
    }
    return acc;
  }, { groups: {}, ungrouped: [] });

  return [...Object.values(result.groups), ...result.ungrouped];
}
console.log(group(data));

  • Related