Search code examples
javascriptarrayslodash

Lodash nested lookup object to array


I have an array of object that contain an array on languages.

 [
    {
        "productId":1,
        "productEmailTypeId":12,
        "languageEmails":[
            {
                "productEmailId":22,
                "languageId":1,
                "body":"some body"
            },
            {
                "productEmailId":33,
                "languageId":3,
                "body":"some body"
            }
        ]
    }
]

I converted this array into a lookup object because it better suits my needs

{
    "12":{
        "productId":1,
        "productEmailTypeId":12,
        "languageEmails":{
            "22":{
                "productEmailId":22,
                "languageId":1,
                "body":"some body"
            },
            "33":{
                "productEmailId":33,
                "languageId":3,
                "body":"some body"
            }
        }
    }
}

My problem is that I have to convert it back to the initial form and can't seem to get it right.

Here's what I tried:

_.chain(emails)
  .toArray()
  .map(item => _.toArray(item))
  .value();

The problem with this is that I loose the other properties (they get merged in the array)


Solution

  • _.toArray(emails).map(item => {
        item.languageEmails = _.toArray(item.languageEmails);
        return item;
    });