Traverse the array containing nested arrays to generate fresh objects in AngularJS

After retrieving an object from my REST API, I need to iterate over the array and create new objects/arrays from it.

The structure of the array is as follows:

orderItem contains menu_modifier_groups, which in turn contain menu_modifier_items.

The hierarchy is: orderItem -> menu_modifier_groups -> menu_modifier_items

orderItem: {
    id: 159
    name: Empanadas (Choice of 2)
    description: Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella
    price: 700
    available: 1
    created_at: 2016-01-31 16:50:31
    updated_at: 2016-01-31 16:50:31
    menu_category_id: 41
    restaurant_id: 11
    menu_modifier_groups:
        [{
            id: 9
            name: Choose 2 Empanadas
			instruction: null
            min_selection_points: 2
            max_selection_points: 2
            force_selection: 1
            created_at: '2016-02-01 01:03:35'
            updated_at: '2016-02-01 01:12:23'
            menu_item_id: 159
            restaurant_id: 11
            menu_modifier_items:
                [{
                    id: 34
                    name: Diced Beef
                    price: 0
					created_at: '2016-02-01 01:04:08'
                    updated_at: '2016-02-01 01:04:08'
                    menu_modifier_group_id: 9
                    restaurant_id: 11
                    menu_item_id: 159
                    selected: true
                 }, {
                    id: 35
                    name: Smoked Salmon & Mozzarella
                    price: 0
					created_at: '2016-02-01 01:04:39'
                    updated_at: '2016-02-01 01:04:37'
                    menu_modifier_group_id: 9
                    restaurant_id: 11
                    menu_item_id: 159
                    selected: true
                 }]
         }]
 }

Upon receiving this data from the REST API, my goal is to transform the orderItem into:

// main item + menu_modifier_items(where selected = true) without menu_modifier_groups

$scope.mainItem = {
    id: 159
    name: Empanadas (Choice of 2)
	description: Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella
	price: 700
    available: 1
    created_at: '2016-01-31 16:50:31'
    updated_at: '2016-01-31 16:50:31'
    menu_category_id: 41
    restaurant_id: 11
    menu_modifier_items: [{
        id: 34
        name: Diced Beef
        price: 0
        created_at: '2016-02-01 01:04:08'
        updated_at: '2016-02-01 01:04:08'
        menu_modifier_group_id: 9
        restaurant_id: 11
        menu_item_id: 159
        selected: true
     },{
        id: 35
        name: Smoked Salmon & Mozzarella
        price: 0
        created_at: '2016-02-01 01:04:39'
        updated_at: '2016-02-01 01:04:37'
        menu_modifier_group_id: 9
        restaurant_id: 11
        menu_item_id: 159
        selected: true
     }]
}

This transformation allows me to work with $http as shown below:

$scope.addItem = function(orderItem) {

//transform orderItem here into mainItem

$http({
    method: 'post',
    url: "http://api.example.com/web/cart/item/add",
    data: $.param({
        'cartItem': $scope.mainItem
    }),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
});
}

Your advice and guidance on this process would be highly appreciated.

Answer №1

When faced with a task like this, you may find that using a JavaScript utility library such as Lodash could be helpful. However, if you prefer to stick to basic JavaScript, here's how you can tackle it.

// Create an array of modifierItems by iterating through the menu_modifier_group entries and selecting only those with selected: true
var modifierItems = [];
for (var i = 0; i < orderItem.menu_modifier_groups.length; i++)
{
    if (orderItem.menu_modifier_groups[i].selected.menu_modifier_items)
    {
       for (var j = 0; j < orderItem.menu_modifier_groups[i].menu_modifier_items.length; j++)
       {
           if(orderItem.menu_modifier_groups[i].menu_modifier_items[j].selected === true)
           {
                 modifierItems.push(orderItem.menu_modifier_groups[i].menu_modifier_items[j]);
            }
        }

    }
}

// Remove menu_modifier_groups and use the remaining orderItem object as $scope.mainItem,
// adding the array of modifier items created earlier as menu_modifier_items
delete orderItem.menu_modifier_groups;
$scope.mainItem = orderItem;
$scope.mainItem.menu_modifier_items = modifierItems;

// Proceed with your $http operations

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

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

Looking for an angular split pane library that is built exclusively for AngularJS without any reliance on other frameworks?

Is there a split-pane library available that can enable me to display 2 tables on a screen and allow users to drag the divider in the middle to adjust the sizes of each table? I have come across libraries such as the shagstrom one that offer this function ...

How to remove an event listener that was added within a function in JavaScript?

I am encountering an issue while trying to remove an event listener that was created inside a function. Oddly enough, it works perfectly when I move the event listener outside of the function. See the example below: <body> <div id='myDiv&apo ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Ways to prompt app.js to invoke an external package

Getting started with a new project. The hosting service I'm using is Passenger, which requires app.js to be in a specific location to work properly. Redux recommends organizing files in self-contained folders. How can I ensure that app.js points to t ...

How can you show a different value in a select menu with AngularJS on selection?

When designing my menu to display US States for selection, I wanted to show both the 2-letter state code and the full name of the state initially. However, once the user selects a state, I only want to display the 2-letter code. This is how my menu looks: ...

Detect mouse events using electron even when the window is not in focus

Is there a way to detect mouse events such as hover and click even when the Electron window is not the active focus? I want to ensure that my buttons' hover and click effects still function properly. Currently, I find that I have to switch back to th ...

Looking to add a button on a PolymerJS page that will allow users to download a PDF file of the report in a row-by-row

I am looking to add a button to a polymerJS webpage that, when clicked, will download a PDF with decorations in a table format containing rows and columns. Can someone guide me on how to achieve this? Thank you in advance. ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

Having issues with C# ASP.Net autocomplete not functioning properly when using Javascript/Json post

I have been working on a c# asp.net usercontrol that requires a functional autocomplete feature. However, I am encountering an ongoing issue where the script appears to be running – with the progress bar spinning – but it consistently returns an ' ...

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

Sending input data to a C function using command line arguments

I am in the process of enhancing my code by introducing functions, and I have encountered an issue that I can't seem to solve. Most of my code seems correct since it runs without the functions I am trying to add. My main method requires 4 arguments - ...

Encountering an issue with NextJS useRouter when it is utilized within a function

I have encountered a puzzling issue that I can't seem to resolve. In my experimentation with NextJS, I am attempting to access the params in the router by utilizing the useRouter hook and integrating it with the querystring plugin to parse the asPath, ...

Automated Recommendation Selector

I'm searching for a JavaScript library that can provide the following functionalities: An auto-suggest dropdown list that uses Ajax to retrieve results from a database. Restricting the user to only select values provided by the Ajax call. Abilit ...

Why do my posts appear twice on the page after submitting a new post? When I refresh the page, the posts seem to duplicate

After submitting the create post controller via POST, the post appears once. However, upon reloading the page using GET, it shows up twice. How can I prevent this duplication and ensure that existing posts are only displayed once? I aim to have the post d ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Fade in text effect using jQuery on a Mac computer

Trying to create a smooth text fading effect across different browsers using jQuery. In the example below, you may notice that during the last part of the animation when the text fades in, the font weight suddenly increases causing a jerky/clunky appearan ...

Tips for preventing the newly updated value from being linked to another array within Angular 13

Currently, I am using angular13 and working on a functionality where there is a button to move items from the left side to the right side. Interestingly, when an item is moved from the left to the right side and then edited under the right side, the edited ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...