Having a dilemma at work with the data I'm receiving from our internal API. It's not in the right format for my needs, so I have to do some transformations.
Decided to utilize Lodash for this task, but currently stuck on a particular issue.
The main problem lies in handling orders where some products are addons to a parent product. While I've succeeded in distinguishing between these two types of products, I'm uncertain about how to attach an "addons" array as a child to the parent product matching the ID.
Below is a simplified example of the desired output:
{
"order": {
"orderLines: [
{
"orderId": "foo",
"addons" [
{
...
}
]
},
{
...
}
]
}
}
Current code snippet:
// TODO:
// Match addons to products based on "connectedTo" => "id", then add matching addons as a new array on parent object
// Base data
const data = { ... }
// Transform data using Lodash library
const travelTimes = data.order.travelTimes.map(item => _.omit(item, ['id']) )
const orderLines = _.merge(data.order.orderLines, travelTimes)
const order = _.omit(data.order, ['orderLines', 'travelTimes'])
const orders = _.assign(order, { orderLines })
const addonGroups = _.groupBy(order.orderLines, 'connectedTo')
const addons = _.omit(addonGroups, 'undefined')
const products = _.pick(addonGroups, 'undefined')
const productGroups = _.groupBy(products.undefined, 'stringId')
console.log(productGroups) // All parent products
console.log(addons) // All addon products
const arr1 = _.values(_.flatMap(productGroups))
const arr2 = _.values(_.flatMap(addons))
Your input and suggestions would be highly valued! Feel free to request further clarification if needed.