Javascript, match checkboxes with JSON Javascript, match checkboxes with JSON json json

Javascript, match checkboxes with JSON


You can filter your array of recipes to only the recipes that includes all the select ingredients, like this:

let filtered = recipes.filter((recipe) => {    return selectedCheckBoxes.every((selected) => {        return recipe.ingredients.some((ingredient) => {            return ingredient['ingredient'] === selected;        });    });});

So, for each one of the recipes we check if every selected ingredient is contained in the recipe. In this case:

  • filter(): Filters out any recipe that does not contain every selected ingredient;
  • every(): Checks if every select ingredient is in the current recipe being evaluated by filter();
  • some(): Checks if some of the recipe's ingredients is equal to the current select ingredient being evaluated by every().

I edited your fiddle so you can see it working: https://jsfiddle.net/byce6vwu/1/

Edit

You can convert the returned array to html like this (i also changed the output div to an ul:

let outputRecipes = '';  filtered.forEach((recipe) => {    let stringIngredients = recipe.ingredients.map((val) => {        return val.ingredient;    }).join(',');        outputRecipes += `<li>${recipe.name}: ${stringIngredients}</li>`;  });    document.getElementById('output').innerHTML = outputRecipes;

I've edited the fiddle: https://jsfiddle.net/ys0qofgm/

So, for each ingredient in the array, we convert the ingredient object: {ingredient: "Cheese"} to only a string "Cheese" and join all the elements of the array using a comma as the separator. Then create a li element for each recipe, and put the recipe string inside of it.


What do you think about this quick suggestion, I know it's not very elegant:

HTML (replace with this)

<ul id="output">The results end up here</ul>

JS

var getRecipesButton = document.getElementById('getRecipesButton');getRecipesButton.addEventListener("click", function(){    let selectedCheckBoxes = selectedBoxes(this.form);    document.getElementById("output").innerHTML = "";  var res = [];  recipes.forEach(function(r,k){    r['ingredients'].forEach(function(i,idx){        if(selectedCheckBoxes.includes(i.ingredient)) {        res.push(r);      }    });  });// remove duplicate then display the recipe with the ingredient    res.filter(function(item, index){      return res.indexOf(item) >= index;    }).forEach(function(r){      var ingredient = r.ingredients.map(function(r) { return r.ingredient}).join(", ");      var name = r.name + " : "+ingredient ;      var ul = document.getElementById("output");      var li = document.createElement('li');      li.appendChild(document.createTextNode(name));      ul.appendChild(li);    });});

Here a working version: https://jsfiddle.net/8esvh65p/


This code will do what you want. It iterates over each ingredient, checking the set of recipes and their ingredients to check if that recipe includes that ingredient. Only recipes which include all the selected ingredients are returned:

//Recipes JSON-string:var recipes = [	{		name:"recipe1",		ingredients:			[				{ingredient:"Cheese"},				{ingredient:"Tomato"},				{ingredient:"Garlic"}			]	},	{		name:"recipe2",		ingredients:			[				{ingredient:"Cheese"},				{ingredient:"Bacon"},				{ingredient:"Paprika"},				{ingredient:"Onion"}			]	},	{		name:"recipe3",		ingredients:			[				{ingredient:"Cheese"},				{ingredient:"Potato"},				{ingredient:"Mayo"},				{ingredient:"Beef"},				{ingredient:"Garlic"},				{ingredient:"Butter"}			]	}];//Test to retrieve single, specific entries://      console.log(recipes[1].ingredients[0].ingredient);//Test to get/return the checked values of the checkboxes:function selectedBoxes(form) {	let selectedBoxesArr = [];	let inputFields = form.getElementsByTagName('input');	let inputFieldsNumber = inputFields.length;	for(let i=0; i<inputFieldsNumber; i++) {		if(			inputFields[i].type == 'checkbox' &&			inputFields[i].checked == true		) selectedBoxesArr.push(inputFields[i].value);	}	return selectedBoxesArr;}var getRecipesButton = document.getElementById('getRecipesButton');getRecipesButton.addEventListener("click", function(){  let selectedCheckBoxes = selectedBoxes(this.form);  let output = document.getElementById('output');  let myRecipes = recipes.filter(r =>     selectedCheckBoxes.every(s =>        r.ingredients.some(i => i.ingredient == s)    )  );  output.innerHTML = myRecipes.map(v => v.name + ': ' + v.ingredients.map(i => i.ingredient).join(', ')).join('<br>');});
<form action="" method="">	<input type="checkbox" value="Cheese">Cheese<br>	<input type="checkbox" value="Tomato">Tomato<br>	<input type="checkbox" value="Garlic">Garlic<br>	<input type="checkbox" value="Bacon">Bacon<br>	<input type="checkbox" value="Paprika">Paprika<br>	<input type="checkbox" value="Onion">Onion<br>	<input type="checkbox" value="Potato">Potato<br>	<input type="checkbox" value="Mayo">Mayo<br>	<input type="checkbox" value="Beef">Beef<br>	<input type="checkbox" value="Garlic">Garlic<br>	<input type="checkbox" value="Butter">Butter<br>	<input type="button" value="Get recipes" id="getRecipesButton"></form><div id="output">The results end up here</div>