Discover content within nested arrays - angularJS

I have a function written in angularJS that utilizes find to verify the presence of an item in an array;

function checkCartItem(item) {
    return $scope.cart[0].cart_items.find(function(itm) {
        return itm.item_id === item.item_id
    });
}

The function, as shown above, takes an item as input and then checks if the item_id of the provided item exists in the items within the cart_items array.

Now, I am looking to enhance this function.

The cart_items array contains a sub array called cart_modifier_items. When a cart_item is passed, it includes the cart_modifier_items. However, my current function only looks for a match in cart_item.

How can I modify this function to also include the cart_modifier_items in the check?

Essentially, I want to validate if the item.item_id matches any item in $scope.cart[0].cart_items - which the function already does.

But, I also need to verify if the item.cart_modifier_item[i] exists in

$scope.cart[0].cart_items[i].cart_modifier_items
where i represents looping through all the cart_items.

Any assistance or guidance on this matter would be highly appreciated.

Data structure of the item

cart_item: [
    {
      "id": 159,
      "item_id": 20,
      "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,
      "cart_modifier_items": [
          {
              "id": 34,
              "item_id": 29,
              "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
          },
          {
              "id": 35,
              "item_id": 10,
              "name": "Smoked Salmon & Mozzarella",
              "price": 0,
              "created_at": "2016-02-01 01:04:37",
              "updated_at": "2016-02-01 01:04:37",
              "menu_modifier_group_id": 9,
              "restaurant_id": 11,
              "menu_item_id": 159
          }
        ]
    }
]

Answer №1

Instead of using find, opt for the standard some method in the following code snippet:

function matchCartItem(item) {
    return $scope.cart[0].cart_items.some(function(itm) {
        return itm.item_id === item.item_id;
    });
}

The some method evaluates if any item in the array meets the specified condition.

Answer №2

To successfully identify the desired cart modifier item, you simply need to iterate through the cart items twice:

var findModifierItem = function(itemId, cartModifierId, cartItems) {
  var itemLength = cartItems.length;
  for (var i = 0; i < itemLength; ++i) {
    if (cartItems[i].id === itemId) {
      var modifierLength = cartItems[i].cartModifierItems.length;
      for (var j = 0; j < modifierLength; ++j) {
        if (cartItems[i].cartModifierItems[j].id == cartModifierId) {
          return true;
        }
      }
    }
  }
  return false;
}

Check out the code in action on Plunker: https://plnkr.co/edit/NVBgdT6ked5gUMtnfKc3?p=preview

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

How can the value be passed as an Array to the data in Vue.js?

Passing the object value as props into my "data" studentId within the form is a key aspect of my project. data() { return { form: new Form({ studentId: [] }) }; }, In the method, the initial values for classlists are set to ...

What is the purpose of using route('next') within ExpressJS?

In the documentation it states: You can have multiple callback functions that act as middleware and can invoke next('route') to skip the remaining route callbacks. This is useful for setting pre-conditions on a route and then passing control t ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

Can icons with an external path be utilized as a src in the manifest.json file within an Angular application?

Let's visualize the setup with two projects - project1 and project2. Each project has its own manifest.json file and the same apple-touch-icon-144x144.png file located in assets/icons directory. -project2 |_src | |_assets | | |_icons | | ...

When sending a POST request to my server and attempting to retrieve the body content, all properties, including arrays, are automatically cast to strings

It recently dawned on me that when I send a POST request like this: async createProduct(){ let formData = new FormData(); formData.append("name", "test") formData.append("price", 150) formDa ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Modify x and y axes in highcharts for stacked columns

Can anyone assist me in finding charts similar to the one shown below? I am interested in utilizing the stacked column charts provided by the highcharts library. However, I need to modify the presentation of the data values as demonstrated in the image. I ...

Maintain the UI actions and status using angular-ui-router

Is it possible to maintain the UI state in angular-ui-router similar to how native apps do? For instance, if I expand an accordion list on the home view, then navigate to another view by clicking on an item within that list, can the accordion still be expa ...

Importing mock data into an AngularJS unit test

Having some trouble setting up my AngularJS application for testing controllers, routes, templates, and more. I'm running into difficulties getting the helper methods from angular-mocks.js to function properly, especially module and inject. I am usin ...

SQL Server transforms column values into column names and then converts them into a JSON array

Imagine a scenario where there is a table called ProductValues with the fields ProductID, Name, and Value: ProductID Name Value 1 Market A 1 Customer B 2 Market C 2 Customer D To group these values by their ProductID and retrieve them as an ...

Understanding the application of hstack in numpy

I need to extract the 4th and 5th columns from a large numpy.ndarray array and create a 2D array with those values. The [i,0] element should correspond to the value in the 4th column and [i,1] should be from the 5th column. I attempted to achieve this usi ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

Vue warning: Issue encountered in created hook - Attempting to access property 'get' of an undefined variable is causing a TypeError

I encountered an error while using axios: [Vue warn]: Error in created hook: "TypeError: Cannot read property 'get' of undefined" export default { methods: { loadUsers(){ axios.get("api/user").then(data => ...

An issue arises when trying to loop using a while loop within an HTML structure

I have a small project with a predefined format, where I need to select a value from a dropdown menu and use that value to fetch data from a database and display it in HTML. While I am able to retrieve the data from the database based on the selected value ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

Errors are being thrown by 'npm run serve' due to the absence of FilterService

I've been working on a project using Vue.js and I keep running into an issue with npm. Every time I install it, I get errors saying that certain files are missing from the node_modules folder. When I try to run npm run serve, I encounter the followin ...

The Angular factory function was unable to be initialized

I recently started learning how to integrate Angularjs with ROR using this helpful tutorial While working on adding a new function to retrieve all posts from the database, I encountered a problem. The page no longer loads when I run the code and the HTML ...