What is the best way to exclude all elements in the array that do not match this specific

For instance, here is a snippet of code that utilizes a JSON object:

"food": {
        "appetizers": [
            {
                "id": 1,
                "image": "../image/calammari.png",
                "title": "rings",
                "price": 11500,
                "ingredient":[{
                    "id" : "0001",
                    "name": "avocado"
                },
                {
                    "id" : "0001",
                    "name": "tomato"
                }
            ]
            },
            {
                "id": 2,
                "image": "../image/food2.png",
                "title": "bang bang",
                "price": 10000,
                "ingredient":[{
                    "id" : "0001",
                    "name": "eggplant"
                },
                {
                    "id" : "0001",
                    "name": "cucumber"
                }
            ]
            }

In this scenario, if the element accessed equals 'tomato', only the food items containing tomato should be displayed.

Here is an example in HTML:

<div ng-repeat="appetizer in appetizers ">
                        <div>
                            <img ng-src="{{appetizer.image}}" />
                           <div >
                                <p >
                                    {{appetizer.title | uppercase}}
                                </p>
                            </div>

Additionally, the following JavaScript logic is used:

var myAccess = ["tomato"];

      $scope.test = [];
      var appetizer = $scope.appetizers;
      for (var i = 0; i < $scope.appetizers.length; i++) {
        for (var j = 0; j < $scope.appetizers[i].ingredient.length; j++) {

            if ($scope.appetizers[i].ingredient[j].name === myAccess) {

// Insert appropriate action here

            }
          }
      }
      return null;    }

If anyone can provide assistance, it would be greatly appreciated!

In summary, when myAccess is set to 'tomato', the script should identify and extract the first appetizer with tomato as an ingredient, pushing only those ingredients with tomato.

Answer №1

To filter items based on ingredients, you can use the filter method along with some or every:

Items that contain some of the specified ingredients:

const data = [{"id":1,"image":"../image/calammari.png","title":"rings","price":11500,"ingredient":[{"id":"0001","name":"avocado"},{"id":"0001","name":"tomato"}]},{"id":2,"image":"../image/food2.png","title":"bang bang","price":10000,"ingredient":[{"id":"0001","name":"eggplant"},{"id":"0001","name":"cucumber"}]}];
const myAccess = ['avocado', 'tomato'];

console.log(
  data.filter(
    (item) => 
      item.ingredient.some(
        (ingredient) => myAccess.includes(ingredient.name)
      )
  )
);

Items that have all of the specified ingredients:

data.filter(
  (item) => 
    myAccess.every(
      (ingredient)=>
        item.ingredient.some(
          (i)=>i.name===ingredient
        )
    )
);

Answer №2

perhaps this information could be of assistance to you

var app=angular.module("myapp",[]);
app.controller("test_ctrl",function($scope){
$scope.appetizers = [];
$scope.temp={
"food": {
"appetizers": [
{
"id": 1,
"image": "../image/calammari.png",
"title": "rings",
"price": 11500,
"ingredient":[
{
"id" : "0001",
"name": "avocado"
},
{
"id" : "0001",
"name": "tomato"
}
]
},
{
"id": 2,
"image": "../image/food2.png",
"title": "bang bang",
"price": 10000,
"ingredient":[
{
"id" : "0001",
"name": "eggplant"
},
{
"id" : "0001",
"name": "cucumber"
}
]
}
]
}
}


var myAccess = ["tomato"];


      var appetizer = $scope.temp.food.appetizers;
      for (var i = 0; i < appetizer.length; i++) {
        for (var j = 0; j < appetizer[i].ingredient.length; j++) {
            if (appetizer[i].ingredient[j].name === myAccess[0]) {
                $scope.appetizers.push(appetizer[i]);

            }
          }
      }
         
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


<div ng-app="myapp" ng-controller="test_ctrl">
<div ng-repeat="appetizer in appetizers ">
    <div>
        <img ng-src="{{appetizer.image}}" />
       <div >
            <p >
                {{appetizer.title | uppercase}}
            </p>
        </div>
    </div>

</div>

Answer №3

Make sure to also refer to the following JavaScript code snippet which may help resolve your issue.

function myFunction() {
    var myAccess = "tomato";
    $scope.test = [];
    var appetizer = $scope.appetizers;
    for (var i = 0; i < $scope.appetizers.length; i++) {
        var flag = 'false';
        for (var j = 0; j < $scope.appetizers[i].ingredient.length; j++) {
            if ($scope.appetizers[i].ingredient[j].name === myAccess) {
                flag = 'true'; // Flag to check if it exists
                break;
            }
        }
        if(flag == 'false') {
            appetizer.splice(index, i); // Remove the item if not found
        }
    }
    $scope.appetizers = appetizer; // Reassign the variable
}

I have introduced a new variable flag to determine whether the array contains the value of myAccess. Using this logic, I removed the index from the array variable appetizer and replaced the scope variable with it.

Please note that I have not tested the code. Feel free to use this logic in your implementation if it seems suitable.

UPDATE - After reviewing @HMR's answer, my code appears to be less effective :)

Answer №4

Insert appetizers into your array in this manner:

function addAppetizer() {
var chosenAppetizer = ["garlic bread"];

  $scope.selectedItems = [];
  var appetizersArray = $scope.appetizers;
  for (var x = 0; x < appetizersArray.length; x++) {
    for (var y = 0; y < appetizersArray[x].ingredientList.length; y++) {

        if (appetizersArray[x].ingredientList[y].title === chosenAppetizer) {

             // Add code here
             $scope.appetizers.push(appetizersArray[x]); // New line of code.
        }
      }
  }
  return null;    
}

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

Using this.el.object3D.position.set(0,0,0) may not function correctly unless a breakpoint is placed in the debugger beforehand

I am trying to attach a door element to the Vive controller's blue box element. Once the door is appended, I attempt to set its position to '0 0 0' using the code "this.el.object3D.position.set(0,0,0)" in order to connect it to the blue box ...

Google Map not rendering correctly when dynamically implemented for the second time

When this specific HTML code is pasted into an .html document and opened directly in a web browser, it showcases the issue I am experiencing. <!DOCTYPE HTML> <html ng-app="myApp"> <head> <link href="https://netdna.bootstrapcdn.com/bo ...

Toggle visibility of button based on current selection

I am currently working on a script that allows users to select and press "Next" to reveal another set of steps. In order to proceed to the next step, I want to have the submit button disabled by default and only enabled if the user has made at least 2 sele ...

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

Host image previews on the server using Dropzone.js

I'm currently utilizing Dropzone.js along with Angular.js for image uploads. However, I haven't been able to figure out a way to upload thumbnails to my server. .dropzone({ url: "/gallery/add", maxFilesize: 100, paramName: "up ...

Certain components cannot be concealed from particular routes

Having an issue with my app where I want to have a different layout for the Login and Register routes compared to the rest of the routes. I've tried implementing conditional logic in the App component to hide certain components based on the route usin ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

What is the process for generating a 3D array consisting of a tuple of arrays using numpy, with each element mirroring the result of np.where function?

I have a 3D array containing values for each element, organized based on their positions in 3D space. My goal is to create a new 3D array that identifies neighbors for each element by storing tuples of arrays, similar to the output of np.where function. Th ...

accessing the offsetTop property of React elements

When working in React, I've noticed that the offsetTop value of an element differs between componentDidMount and componentDidUpdate. This is surprising to me because I believed componentDidMount occurs after render, meaning the DOM elements should be ...

Is there a way to customize or change the default data parsing and object creation behavior of jQuery's $.ajax method?

I am currently trying to fetch geojson data from my server using $.getJSON or $.ajax, and then display it on google maps with the help of map.data.loadGeoJson(data). The data is successfully loaded when I use map.data.loadGeoJson('/static/json/data.js ...

Modifying the Data in the JSON_ARRAY Mysql 8.0

My current situation involves updating the hourly rate for user BOB to 600. I need to extract the hourly rate from the following JSON array specifically for the user BOB. @data = [{ "Subject": "Maths", "type": "paid", "tutor": "MARY", "hourly_rate": " ...

What is the proper way to provide JSON input for a PUT JAX-RS API that accepts data of type Map<Person, Person>?

I am working on a JAX-RS REST endpoint of PUT type where I need to pass a Map to the API. @PUT @Path("/some/path") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType ...

Steps to display a table upon clicking the submit button in a form

I am currently in the process of developing a project that will showcase a teacher's timetable when the user inputs their faculty ID. I am aiming to have the table displayed only after the user clicks the submit button, rather than presenting an empty ...

Unable to toggle visibility of image

I integrated the jquery.smoothZoom.min.js plugin for zooming and panning images successfully in my project. Now, I am attempting to create a carousel functionality (<,>.i.e. corousal) to use it with multiple images. However, when I added the correspo ...

Combining the powers of $.get and $.ready

Basically, I am facing an issue with my ajax call where sometimes it completes before the page is fully loaded. I attempted to use $( fn ) to wrap the callback function, but unfortunately, the callback does not trigger if the page is already loaded. Does a ...

Arrange the strings in the json data based on their frequency in descending order while maintaining the original sequence of keys in

I am working with a JSON file that contains orders in arrays under the same key. [ { "order":["Order1"] }, { "order":["Order2"] }, { "order":["Order2","Order3"] }, { "order":["Order1","Order2"] }, { ...

jQuery post method not transmitting POST data successfully

const link = 'http://www.example.com/maketransaction.php?validate=1&key=123'; const amount = 50; const userID = 5; const requestData = {transactionAmount:amount, ID:userID, tag:null}; $(document).ready(function(){ $.ajax({ 'u ...

What is the best way to incorporate PHP code within a JavaScript function?

Is it possible to dynamically append the uploaded file name to the list displayed in ('.list')? The challenge lies in passing $_FILES["fileImage"]["name"] as an argument to a separate JavaScript function for appending, especially since the PHP sc ...

jQuery UI Slider is malfunctioning (code example included)

I've implemented a jQuery UI slider on my website, and it's functioning quite well. You can check out the slider HERE. However, I've noticed that when I click on 'back to the top', the page smoothly scrolls up. But when I use the ...

When Utilizing an async Task Method, DbContext is Properly Disposed

Currently, I have set up an async Task method to handle the IAuthenticationFilter interface. After logging in successfully, I can access an API with no issues when it has this attribute. However, if I revisit the API later on, an exception is thrown. publ ...