Fill tree json data to dropdown box - javascript

I have json data in tree format:
[
{
"beer_names": [
"Apple Ale",
"Bad Seed Pumpkin Ale"
],
"brewery": "Basil T's Brew Pub and Italian Grill"
},
{
"beer_names": [
"5 C's IPA",
"Bottle Rocket IPA",
"Kate The Great Russian Imperial Stout",
"Wheat Wine"
],
"brewery": "Portsmouth Brewery"
},
{
"beer_names": [
"Black Forest Dunkelweizen",
"Equinox E.S.B.",
"Evolutionary IPA",
"G.E. Lite",
"Nut Brown",
"Red",
"Smoked Porter"
],
"brewery": "Glen Ellyn Sports Brew"
}
]
So I want to fill this data to Dropdown box like this:
--Basil T's Brew Pub and Italian Grill
--------Apple Ale
--------Bad Seed Pumpkin Ale
--Portsmouth Brewery
--------5 C's IPA
--------Bottle Rocket IPA
--------Wheat Wine
--------Kate The Great Russian Imperial Stout
--Glen Ellyn Sports Brew
--------Black Forest Dunkelweizen
--------Equinox E.S.B.
--------Evolutionary IPA
--------G.E. Lite
--------Nut Brown
--------Red
--------Smoked Porter
Or a tree view allow for select value name of child equipment?

Here you are:
var data = [{
"beer_names": [
"Apple Ale",
"Bad Seed Pumpkin Ale"
],
"brewery": "Basil T's Brew Pub and Italian Grill"
}, {
"beer_names": [
"5 C's IPA",
"Bottle Rocket IPA",
"Kate The Great Russian Imperial Stout",
"Wheat Wine"
],
"brewery": "Portsmouth Brewery"
}, {
"beer_names": [
"Black Forest Dunkelweizen",
"Equinox E.S.B.",
"Evolutionary IPA",
"G.E. Lite",
"Nut Brown",
"Red",
"Smoked Porter"
],
"brewery": "Glen Ellyn Sports Brew"
}];
$.each(data, function(index, value) {
var str = '<optgroup label="' + value["brewery"] + '">';
$.each(value['beer_names'], function(index, value) {
str += '<option value="' + value + '">' + value + '</option>';
});
str += '</select>';
$('select').append(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
Hope this helps.

You can see this link :
http://www.jeasyui.com/demo/main/index.php?plugin=ComboBox
then you select Group ComboBox from left panel.
Maybe help you

Related

How to implement a 'contains' search in JavaScript

I'm creating a search box that allows you to search for different companies. I'd like the search box to perform a 'contains' search. For example, let's say that I want to look up the company ExxonMobil Oil Corp. Typing in any of the following should include the company in the list of results (this isn't exhaustive):
oil
corp
oil corp
exxonmobil
exxonmobil oil
exxonmobil oil corp
The words don't have to be complete, just to be clear. The phrase 'oil co', for instance, should still bring up a result.
Typing in 'exxonmobil corp', however, will not bring up the company as a result since 'corp' does not immediately follow 'exxonmobil' in the company's name.
Is there a go-to method for implementing this type of search, keeping time efficiency in mind? In my case, there can be thousands of companies to search through. And I'd like to be able to display the list of results on the fly as the user is typing into the search box.
I'm aware of the trie data structure, but from what I've read, it seems to work best for 'starts with' searches. So it wouldn't match searches like 'oil corp', 'oil', or 'corp' with ExxonMobil Oil Corp. Perhaps there's a way to tweak the trie to do as I want, but I'm just not sure if that's the best way to go.
Thank you for the responses. A few of you suggested looking into String.prototype.includes(). I gave that a try, and it does seem to work well with no performance issues.
100 companies is fast.
const companies = [
"Arcade Flower Shop",
"Madam Malkin's Robes for All Occasions",
"Victoria's Circuit",
"33ยข Store",
"El Banco Corrupto",
"Silver Shamrock",
"Stay Puft Corporation",
"Wonka Industries",
"Blue Moon Detective Agency",
"The Foundation",
"Macmillan Toys",
"The Reef",
"Merrick BioTech",
"The Peach Pit",
"The Korova Milkbar",
"Paper Street Soap Company",
"Mel's Diner",
"Dunder Miflin",
"The Everything Store",
"Rodbell's",
"Rex Kwan Do",
"The Fairly Oddparents",
"Vitameatavegamin",
"Bushwood Country Club",
"Consumer Recreation Services",
"The Rusty Anchor",
"IPS (International Parcel Services)",
"Pendant Publishing",
"Lacuna Inc.",
"H.A.L. Labs",
"Life Extension",
"Rekall",
"Bluehound Bus Line",
"Atlantic American Airlines",
"KACL",
"Flingers",
"Burrito Explosion",
"Fatso's",
"The Max",
"McDowell's",
"Bada Bing",
"Wu-Tang Financial",
"Wally World",
"The Dharma Initiative",
"The Leftorium",
"Edna's Edibles",
"Daily Planet",
"21 Jump Street",
"The Enterprise",
"Powell Family",
"Central Perk",
"Night Court",
"Arnold's Drive-In",
"WKRP",
"Moe's Tavern",
"Lomax Industries",
"Hudsucker Industries",
"Los Pollos Hermanos",
"Chubby's",
"Mugatu Industries",
"The Daily Bugle",
"Globex Corporation",
"Entertainment 720",
"Soylent Corporation",
"SS Minnow",
"TGS with Tracy Jordan",
"Grace Adler Designs",
"Pierce & Pierce",
"Wayne Enterprises",
"Cheers",
"Goliath National Bank",
"Pricemart",
"Career Transitions Corporation",
"Bluth's Original Frozen Banana",
"Livingston",
"Luke's Diner",
"Adventureland",
"Buy-N-Large",
"Average Joe's Gym",
"Duff Beer",
"Michael Scott Paper Company",
"Brawndo",
"Fisher & Sons",
"Mitch and Murray",
"Multi National United",
"Oscorp",
"Pizza Planet",
"Momcorp",
"Ewing Oil",
"Prestige Worldwide",
"Tyrell Corporation",
"Omni Consumer Products",
"Monsters Inc.",
"Ghostbusters",
"Pied Piper",
"TelAmeriCorp",
"Yakonomo Corporation",
"Mega Lo Mart",
"Vandelay Industries",
"Frosty Palace",
"Sterling Cooper Draper Pryce",
"M.I.B.",
"The Smash Club"
];
const search = document.getElementById("search");
const output = document.getElementById("output");
const filter = (evt) => {
const val = evt.target.value;
if (val.length < 1) return output.value = "";
output.value = companies.filter(company => company.toLowerCase().includes(val.toLowerCase())).join("\n");
}
search.addEventListener("keyup", filter);
input,
textarea {
margin-top: 1em;
}
<link href="https://unpkg.com/marx-css/css/marx.min.css" rel="stylesheet" />
<main>
<input type="text" id="search" />
<textarea rows=4 id="output"></textarea>
</main>

replace a key value pair from a GET request without mutating the original JSON

I have a task to return some an object by name of recipe and include a list of it's ingredients and also an object that replaces the instructions with a key value pair of "numSteps": count_of_instruction_steps. I am having a hard time with removing the key of "instructions" for the result.
This is the .json file of recipes:
{
"recipes": [
{
"name": "scrambledEggs",
"ingredients": [
"1 tsp oil",
"2 eggs",
"salt"
],
"instructions": [
"Beat eggs with salt",
"Heat oil in pan",
"Add eggs to pan when hot",
"Gather eggs into curds, remove when cooked",
"Salt to taste and enjoy"
]
},
{
"name": "garlicPasta",
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"instructions": [
"Heat garlic in olive oil",
"Boil water in pot",
"Add pasta to boiling water",
"Remove pasta from water and mix with garlic olive oil",
"Salt to taste and enjoy"
]
},
{
"name": "chai",
"ingredients": [
"400mL water",
"100mL milk",
"5g chai masala",
"2 tea bags or 20 g loose tea leaves"
],
"instructions": [
"Heat water until 80 C",
"Add milk, heat until 80 C",
"Add tea leaves/tea bags, chai masala; mix and steep for 3-4 minutes",
"Remove mixture from heat; strain and enjoy"
]
}
]
}
The task is the following:
A GET request to http://localhost:3000/recipes/details/garlicPasta should return, if recipe exists, this .json:
Response body (JSON):
{
"details":
{
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"numSteps":5
}
}
Status: 200
And should return this if it does not exist:
Response body (JSON): {}
Status: 200
This is what I am actually getting:
{
name: "garlicPasta",
ingredients: [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
instructions: {
numSteps: 5
}
}
My code is the following:
app.get('/recipes/details/:name', (req, res) => {
let count = 0
const numSteps = {}
const recipe = recipes.find(r => r.name === req.params.name)
const instructions = recipes.map(r => {
if(r.name === req.params.name){
for(let instruction of r.instructions){
count += 1
}
}
})
recipe.instructions = {"numSteps": count}
res.status(200).send(recipe);
})
I wouldn't try to return a modified "recipe" object since the shape of the response you need is different. You can use your existing code to find the correct recipe, and then just create a new object with the response properties you want. Note that you can just use recipe.instructions.length to know how many steps there are.
app.get('/recipes/details/:name', (req, res) => {
let count = 0;
const recipe = recipes.find(r => r.name === req.params.name);
const output = {
details: {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
}
};
res.status(200).send(output);
})
You're not creating the details property, and you're adding an instructions property in the result that you don't want.
There's no need to loop to count numSteps, you can just use r.instructions.length. And once you find the recipe with recipes.find(), you don't need another loop to find the recipe name.
You're not checking whether the recipe can be found, so that you return {} in that case.
app.get('/recipes/details/:name', (req, res) => {
const recipe = recipes.find(r => r.name === req.params.name);
let result = {};
if (recipe) {
result.details = {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
};
}
res.status(200).send(recipe);
})

Array issue in JS

I ran into an issue where I can't figure out how to pull the data from a TPA API. Would greatly appreciate any help!:)
This is the link to the API: https://www.themealdb.com/api/json/v1/1/random.php
I'm trying to pull out the name of the meal, instructions picture, and the source of the recipe, using an ajax method.
This is the basic structure I have right now:
let randomGenerator = function(){
$.ajax({
method: "GET",
url: "https://www.themealdb.com/api/json/v1/1/random.php",
success: function(r){
console.log(r);
let meals = r["meals"]
let pic = meals[34]
let name = meals[23]
let instructions = meals[29]
let source = meals[52]
$("#random-name").html(name)
$("#random-description").html(instructions)
$("#random-source").html(source)
$("#random-photo").attr("src", pic)
},
error: function(data){
console.log(data);
}
});
}
This is the result from the API when fetched from above link:
{
"meals": [
{
"idMeal": "52964",
"strMeal": "Smoked Haddock Kedgeree",
"strDrinkAlternate": null,
"strCategory": "Breakfast",
"strArea": "Indian",
"strInstructions": "Melt 50g butter in a large saucepan (about 20cm across), add 1 finely chopped medium onion and cook gently over a medium heat for 5 minutes, until softened but not browned.\r\n\r\nStir in 3 split cardamom pods, \u00bc tsp turmeric, 1 small cinnamon stick and 2 bay leaves, then cook for 1 minute.\r\n\r\nTip in 450g basmati rice and stir until it is all well coated in the spicy butter.\r\n\r\nPour in 1 litre chicken or fish stock, add \u00bd teaspoon salt and bring to the boil, stir once to release any rice from the bottom of the pan. Cover with a close-fitting lid, reduce the heat to low and leave to cook very gently for 12 minutes.\r\n\r\nMeanwhile, bring some water to the boil in a large shallow pan. Add 750g un-dyed smoked haddock fillet and simmer for 4 minutes, until the fish is just cooked. Lift it out onto a plate and leave until cool enough to handle.\r\n\r\nHard-boil 3 eggs for 8 minutes.\r\n\r\nFlake the fish, discarding any skin and bones. Drain the eggs, cool slightly, then peel and chop.\u2028\r\n\r\nUncover the rice and remove the bay leaves, cinnamon stick and cardamom pods if you wish to. Gently fork in the fish and the chopped eggs, cover again and return to the heat for 2-3 minutes, or until the fish has heated through.\r\n\r\nGently stir in almost all the 3 tbsp chopped fresh parsley, and season with a little salt and black pepper to taste. Serve scattered with the remaining parsley and garnished with 1 lemon, cut into wedges.",
"strMealThumb": "https:\/\/www.themealdb.com\/images\/media\/meals\/1550441275.jpg",
"strTags": "Brunch,Fish,Fusion",
"strYoutube": "https:\/\/www.youtube.com\/watch?v=QqdzDCWS4gQ",
"strIngredient1": "Butter",
"strIngredient2": "Onion",
"strIngredient3": "Cardamom",
"strIngredient4": "Turmeric",
"strIngredient5": "Cinnamon Stick",
"strIngredient6": "Bay Leaf",
"strIngredient7": "Basmati Rice",
"strIngredient8": "Chicken Stock",
"strIngredient9": "Smoked Haddock",
"strIngredient10": "Eggs",
"strIngredient11": "Parsley",
"strIngredient12": "Lemon",
"strIngredient13": "",
"strIngredient14": "",
"strIngredient15": "",
"strIngredient16": "",
"strIngredient17": "",
"strIngredient18": "",
"strIngredient19": "",
"strIngredient20": "",
"strMeasure1": "50g",
"strMeasure2": "1 chopped",
"strMeasure3": "3 Pods",
"strMeasure4": "1\/4 tsp",
"strMeasure5": "1 small",
"strMeasure6": "Sprigs of fresh",
"strMeasure7": "450g",
"strMeasure8": "1 Litre",
"strMeasure9": "750g",
"strMeasure10": "3",
"strMeasure11": "3 tblsp chopped",
"strMeasure12": "1 chopped",
"strMeasure13": " ",
"strMeasure14": " ",
"strMeasure15": " ",
"strMeasure16": " ",
"strMeasure17": " ",
"strMeasure18": " ",
"strMeasure19": " ",
"strMeasure20": " ",
"strSource": "https:\/\/www.bbcgoodfood.com\/recipes\/2256\/smoked-haddock-kedgeree",
"strImageSource": null,
"strCreativeCommonsConfirmed": null,
"dateModified": null
}
]
}
I keep getting undefined as the array has only one object -> 0, that one random meal, so I'm very confused about how to pull that info out. I created a button that should generate these things on the page, hence the HTML inside.
The return has an array of meals, so just access meals[0].whatever_var_you_want
eg.
$.ajax({
method: "GET",
url: "https://www.themealdb.com/api/json/v1/1/random.php",
success: function(r){
var meal = r.meals[0];
$("#random-name").html(meal.strMeal)
$("#random-description").html(meal.strInstructions);
$("#random-source").html(meal.strSource)
$("#random-photo").attr("src", meal.strMealThumb)
},
error: function(data){
console.log(data);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="random-name"></p>
<p id="random-description"></p>
<p id="random-source"></p>
<img id="random-photo"/>
Per www.themealdb.com:
Lookup a single random meal
www.themealdb.com/api/json/v1/1/random.php
Lookup a selection of 10
random meals (only available to $2+ Patreon supporters)
www.themealdb.com/api/json/v1/1/randomselection.php
So it is expected to have only one object in the array. To have multiple random selections you have to subscribe. And probably your code would look a bit like:
$.ajax({
method: "GET",
url: "https://www.themealdb.com/api/json/v1/1/randomselection.php", //needs subscription
success: function(r){
for (let i=0; i<r["meals"].length; i++) { let meal = r["meals"][i].idMeal; let name=r["meals"][i].strMeal; // ... } }
},
error: function(data){
console.log(data);
}
});
You should be able to access the meal using the syntax r["meals"][0].
Once you have the meal object, you can get the image, name, instructions and source using strMealThumb, strName, strInstructions and strSource respectively.
$.ajax({
method: "GET",
url: "https://www.themealdb.com/api/json/v1/1/random.php",
success: function(r) {
let meal = r["meals"][0];
let pic = meal.strMealThumb;
let name = meal.strMeal;
let instructions = meal.strInstructions;
let source = meal.strSource
$("#random-name").html(name)
$("#random-description").html(instructions)
$("#random-source").html(source)
$("#random-photo").attr("src", pic)
},
error: function(data){
console.log(data);
}
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<img id="random-photo" width="80px"/><br>
<b>Name:</b><p id="random-name"></p>
<b>Source:</b><p id="random-source"></p>
<b>Instructions:</b><p id="random-description"></p>

inner string array filter in array object with string arrry

var mainobj=[[{
"title": "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
"category": [
"Dapper Labs",
" Brud",
" Sorare",
" Bundesliga",
" Etched",
" Hockey Diversity Alliance",
" Archdiocese of Bangkok NFT"
],
"description": "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
},
{
"title": "Bitcoin returns to $1T asset as BTC price blasts to $55K",
"category": [
"Bitcoin",
" BTC price"
],
"description": "Bitcoin returns to $1T asset as BTC price blasts to $55K",
}]]
var categoryfilterArray=['Bitcoin','Bundesliga','Sorare']
i need filter which match categoryfilterArray in mainobj
First, I'm assuming you don't actually have an array containing another array, rather a single array of objects, as such:
const mainobj = [
{
title: "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
category: [
"Dapper Labs",
"Brud",
"Sorare",
"Bundesliga",
"Etched",
"Hockey Diversity Alliance",
"Archdiocese of Bangkok NFT"
],
description: "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
},
{
title: "Bitcoin returns to $1T asset as BTC price blasts to $55K",
category: [
"Bitcoin",
"BTC price"
],
description: "Bitcoin returns to $1T asset as BTC price blasts to $55K",
}
];
From there, you can look at the intersection of the category array and your categoryfilterArray using a function like so:
const arrayIntersection = (array1, array2) => {
return array1.filter(x => array2.includes(x));
};
Then it comes down to how you compare the intersection.
If you're trying find objects where the categories contains all of the categoryfilterArray values, you would compare the intersecting array as a string:
const matchingObj = mainobj.filter(obj => {
return JSON.stringify(arrayIntersection(obj.category, categoryfilterArray)) === JSON.stringify(categoryfilterArray);
});
If you're only looking for one or more of the target categories in the intersection, you can use a boolean conversion:
const matchingObj = mainobj.filter(obj => {
return Boolean(arrayIntersection(obj.category, categoryfilterArray).length);
});
Any intersection length greater than 0 will return true, and return the object in the filter. Alternatively, you can check for arrayIntersection(obj.category, categoryfilterArray).length > 0.
Working examples: https://stackblitz.com/edit/angular-ivy-hew9bq?file=src/app/app.component.ts

Check if a array is contained in another

Im struggling with a piece of code i have below and cant seam to find something like it anywhere on stacks.
I have tried using the JavaScript .indexof(is returning all that doesn't contain variables) as well as the .match(shows all even if contain part of the word. i need it to be exact for obvious reasons) and even jquery.
I was wondering if anyone can help me.
I have a script that pulls data from the server into the following array.
from there i need to be able to compare this array with data that is on the page. if it exists in the server i want to highlight the checkbox i have created. when i did .match it found all variables that contained say the characters foo but i need exact matches not just if it contains.
see below for what i currently have. (note that the variables aren't set in stone and some may be different that will be contained in others which is why they need to be exact)
var industriesget = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing & Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate & Banking", "Agriculture & Fishing", "Communications", "Manufacturing", "Mining", "Entertainment & Gambling", "Retail Sales", "Signage & Fitouts", "Construction", "Transportation", "Public Utilities", "Education" ];
for ( var i = 0; i < industries.length; i++ ) {
//another for loop to run through the matches?
if..........
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-align: center;' name='products' id='" + industries[ i ] + "' checked></label>" );
else{
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-
}
}
Is this what you are looking for? This is simplest way.
var industriesget = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing & Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate & Banking", "Agriculture & Fishing", "Communications", "Manufacturing", "Mining", "Entertainment & Gambling", "Retail Sales", "Signage & Fitouts", "Construction", "Transportation", "Public Utilities", "Education" ];
for ( var i = 0; i < industries.length; i++ ) {
//another for loop to run through the matches?
if(industriesget.indexOf(industries[i])!== -1)
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-align: center;' name='products' id='" + industries[ i ] + "' checked></label>" );
else{
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-")
}
}
If you want to find whether industriesget is subset of industries, then try using
var intersectionIndustries = industries.filter(function(n) {
return industriesget.indexOf(n) !== -1;
});
and check
(intersectionIndustries.length == industriesget.length)
,if true then its subset, else there are non existent entries in industries get.
Use this:
pass two arrays to this function and check if the flag is true or not:
var industriesget = [ "Servers & Software", "Environmental
Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels
& Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing &
Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate &
Banking", "Agriculture & Fishing", "Communications", "Manufacturing",
"Mining", "Entertainment & Gambling", "Retail Sales", "Signage &
Fitouts",
"Construction", "Transportation", "Public Utilities", "Education" ];
if(arr(industriesget,industries)) {
alert("contains");
}
Where our function is:
function arr(industriesget,industries)
{
var flag=false;
for(var i=0;i<industriesget.length;i++)
{
if(industries.includes(industriesget[i])) {
flag = true;
}
}
return flag;
}

Categories

Resources