CornelC
CornelC

Reputation: 5254

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)

Upvotes: 0

Views: 59

Answers (2)

Adriano Valente
Adriano Valente

Reputation: 538

Although it's a little verbose, you can always use the reduce method twice to get the transformation you want:

const oldFormat = _.reduce(emails, function (acc, product) {
   return acc.concat({
     productId: product.productId,
     productEmailTypeId: product.productEmailTypeId,
     languageEmails: _.reduce(product.languageEmails, function (acc, language) {
      return acc.concat({
        productEmailId: language.productEmailId,
        languageId: language.languageId,
        body: language.body
      })
     }, [])
   })
}, [])

Upvotes: 2

sempasha
sempasha

Reputation: 623

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

Upvotes: 1

Related Questions