Utilizing Lodash to append an object to a parent array depending on its IDs

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))

Code available on Codepen.io

Your input and suggestions would be highly valued! Feel free to request further clarification if needed.

Answer №1

Uncertain if I grasped the expected outcome correctly, but I decided to give it a shot nonetheless.

const linesOfOrder = _(data.order.orderLines)
    .map(item => {
        if (!item.connectedTo) return _.assignIn(item, { extras: [] });

        const match = _.find(data.order.orderLines, { id: item.connectedTo });
        match.extras = match.extras || [];
        match.extras.push(item);

        return null;
    })
    .compact()
    .value();

View the result here: https://codepen.io/andreiho/pen/YEzQRd?editors=0012

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What makes .html effective while innerHTML or appendChild do not have the same impact?

Currently, I am facing a challenge where I am attempting to incorporate an ajax response into a div that contains HTML code involving tables, forms, and more. After testing in Firefox, the innerHTML method worked flawlessly. However, Internet Explorer pre ...

Tips for setting discrete mapper style in cytoscapejs?

Currently, I am defining the style of cytoscape.js through CSS and converting it to JSON format using this resource. My goal is to implement a discrete mapper for styling. It's similar to the scenario discussed in How to use a descreteMapper like on c ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

Presenting the correct error notification if the JSON data fails to load in an HTML webpage

Here is a sample JSON data: [ { "componentid": 4, "displayImageUrl": "https://via.placeholder.com/350x200", "title": "theme", "shortdesc": "to set theme for different applications" }, { "componentid": ...

Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only ...

Ways to track down an ajax error response?

Whenever I encounter an AJAX error response with jQuery, the following log is displayed: jquery.js:8630 OPTIONS http://10.0.1.108:8000/api/v1.0/auth/ net::ERR_CONNECTION_REFUSED Object {readyState: 0, status: 0, statusText: "error"} Within my object, the ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Error message encountered: The ReactJS application is unable to locate the module 'webpack' within the cjs/loader.js file

I have come across various links and discussions on this issue, but most of them pertain to Angular. However, the problem I am encountering is specific to ReactJS. The primary error I am facing is: Error: Cannot find module 'webpack' The Requ ...

How to Verify JIRA REST API Authorization using jsonlite::fromJSON in R?

Trying to retrieve JIRA issue details using the jsonlite library has been unsuccessful with the following code: library(jsonlite) jiradata <- fromJSON("https://xxxxxx.atlassian.net/rest/api/latest/search?jql=project=DATAX AND key=DATAX-1234") An e ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

How can we utilize data retrieved from Mongodb in Express and pass it to a Jade view using the res.render function?

Within my node/express application, I need to pass data retrieved from mongoose to my jade view. The code below in routes.js accomplishes this task: app.get('/newrequest', function (req, res) { Account.find({}, function (err, data) { ...

Disregard the Json information if the property is not present

I attempted to retrieve the id Field dynamic post = fb.Get("/" + radListControl2.SelectedItem + "/feed?fields=message"); int count = (int)post.data.Count; for (int i = 0; i < count; i++) { radListControl1.Items.Add(Convert.ToString(post.data[i].i ...

Displaying colors using Javascript

When using node.js to create an HTML file from a js file, I am encountering an issue where the colors are not displaying in the output. I have generated hex values for the colors, but they do not appear in the HTML file as expected. var format; function ...

Issue: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin is a required field and must be provided

While developing my Shopify App using Koa and Nextjs, I encountered the following error: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin must be provided The behavior of the app is a bit odd as it works fine when accessed for the first time. Howev ...

The database is not displaying any information on the webpage

Upon loading my home.php page, the intention is to display the data from the 'blog_post' table in the database. However, despite the record being inserted correctly, no data is being shown on the page. I have searched for solutions to this issue ...

What is the best way to integrate a new unique identifier into an existing MongoDB document using NodeJS?

I am looking to add up a field in a document when I input a new entry that has a replicated unique id. This is the code I have so far: MongoClient.connect(process.env.MONGODB_URI || process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...

Does the JSON property that exists escape NodeJS's watchful eye?

I recently encountered an unexpected issue with a piece of code that had been functioning flawlessly for weeks. In the request below and snippet of the response: //request let campaignRes = request('POST', reqUrl, campaignOptions); //response ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...