Skip to content

Any nice way to groupBy while transforming values with lodash

I am inexperienced with lodash, but I believe it can help me transform data into a desired format. I have tried varying level of methods described in the documentation, but I can not wrap my head around everything. I’ve looked here on SO, a few blogs, and the documentation. I have tried combining groupby and map, but I was unable to resolve the issue. I was also unsure how to log the steps.

Given an array of objects like this:

[
    {
        "parent": "app",
        "value": "id"
        "label": "1",
    },
    {
        "parent": "app",
        "value": "title"
        "label": "Page",
    },
    {
        "parent": "app",
        "value": "description"
        "label": "Desc page",
    },
    {
        "parent": "home",
        "value": "id"
        "label": "2",
    },
    {
        "parent": "home",
        "value": "title"
        "label": "Home",
    },
    {
        "parent": "home",
        "value": "description"
        "label": "Desc home",
    }
]

I would like to convert it to this:

{
   "app": {
      "id": "1",
      "title": "Page",
      "description": "Desc page"
   },
   "home": {
      "id": "2",
      "title": "Home",
      "description": "Desc home"
   }
}

Can anyone point me in the right direction?

Answer

You don’t need lodash to accomplish such behavior. You can easily do this with a reduce.

const values = [
    {
        "parent": "app",
        "value": "id",
        "label": "1",
    },
    {
        "parent": "app",
        "value": "title",
        "label": "Page",
    },
    {
        "parent": "app",
        "value": "description",
        "label": "Desc page",
    },
    {
        "parent": "home",
        "value": "id",
        "label": "2",
    },
    {
        "parent": "home",
        "value": "title",
        "label": "Home",
    },
    {
        "parent": "home",
        "value": "description",
        "label": "Desc home",
    }
];

const mappedValues = values.reduce((acc, val) => {
  acc[val.parent] = acc[val.parent] || {};
  acc[val.parent][val.value] = val.label;
  return acc;
}, {});

console.log(mappedValues);