Rendering JSON array in React component - javascript

I am trying to display an array of strings coming from an API. But I am not able to iterate through that array. If I pass the whole array inside HTML tag then it is rendering as a string.
For example: <div>{data.list.ingredients}</div> is working and displaying as a string. If I try to console this data.list.ingredients[0] it is throwing an error:
Cannot find 0 of undefined
My array:
{
"_id": "5b5446df2c89ab3d0e8d5526",
"title": "Chicken with Mustard Cream Sauce",
"vegetarian": false,
"ingredients": [
"4 whole Boneless Skinless Chicken Breasts",
"2 Tablespoons Olive Oil",
"2 Tablespoons Butter",
"3 whole Garlic Cloves Minced",
"1 cup Brandy",
"1 Tablespoon (heaping) Dijon Mustard",
"1 Tablespoon (heaping) Grainy Mustard",
"1/4 cup (to 1/2) Heavy Cream",
"1/4 cup (to 1/2) Chicken Broth",
"Salt And Pepper"
],
"image_url": "http://static.food2fork.com/chickenmustarde587.jpg",
"steps": [
"Amount of cream and broth has slightly decreased add more as needed",
"Cut the chicken breasts in half lengthwise so that you have eight smaller thinner chicken cutlets Salt and pepper both sides",
"Heat oil and butter in a large skillet over mediumhigh heat Cook cutlets on both sides until nice and golden brown and cooked through Remove chicken from the skillet and keep on a plate",
"Reduce the heat to medium Add the garlic to the pan and saute it for a minute stirring to make sure it wont burn Next pour in the brandy or wine if using being careful if cooking over an open flame Then just let the booze bubble up and cook until its reduced by half",
"Throw in the mustards and stir to combine then pour in the cream Stir in chicken broth adding more if the sauce seems too thick Taste sauce and adjust whatever you think it needs Add chicken breasts back to the pan nestling them into the sauce Allow sauce to cook for another few minutes shaking the pan if needed to move things around",
"Serve chicken with a green salad spooning the sauce over the top"
],
"serving": 5,
"cooking_time": 20
}

function renderData(){
let array = ['a','b','c','d' ];
return array.map((item, index) => <div key={index}>{ item }</div>);
}

I am assuming you are using axios (API component) so in your case you can get the result as follows:
axios.get('/youringredients.json')
.then(res => {
const ingredient = res.data.list.ingredients[0];
console.log(ingredient);
});
you can use ingredient in your state also.

Related

how to split array of strings, delete, and assign new array to same array

I want to delete items in an array that include('https://www.agci.org').
I am splitting the array first with ('>') and then using that to search each string with the includes function. I want to delete the ones that include a url and then use the array with the deleted items and set it back to arr[i].authors. Idk why spl = arr[i].authors line isnt working when its still within the if statement/function
for(var i=0, len = arr.length; i < len; i++){
var spl = arr[i].authors[0].split('>');
spl.forEach(function(item){
if(item.includes('https://www.agci.org')){
delete item;
spl = arr[i].authors
}
})
}
for(var i=0, len = arr.length; i < len; i++){
var spl = arr[i].authors[0].split('>');
spl.forEach(function(item){
if(item.includes('https://www.agci.org')){
result = spl.filter(item)
arr[i].authors = result;
}
})
}
my arrays look like this. they are random arrays that i need to sort and filter through
arr = [
{
"post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate",
"authors":
[
"https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"
]
},
{
"post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics",
"authors":
[
"https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors":
[
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors":
[
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
}
]
I want them to look like this but idk if theres a way to filter the author names because they include the positions as well.
arr = [
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
Ladd Keith,David Hondula,Hunter Jones,Sara Meerow,V. Kelly Turner"
]
}
]
Possibly just a case for RegExp? Here using String.prototype.match().
const arr = [{ "post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate", "authors": ["https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"] }, { "post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics", "authors": ["https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "] }, { "post_title": "Advancing the Theory and Practice of Urban Heat Resilience", "authors": ["https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"] }, { "post_title": "Advancing the Theory and Practice of Urban Heat Resilience", "authors": ["https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"] }];
for (const post of arr) {
post.authors = post.authors[0].match(/(?<=">(?!https))[^>]+/g)
}
console.log(arr);
Use filter() to remove the URLs, then use join() to concatenate the remaining elements back into a string.
arr = [{
"post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate",
"authors": [
"https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"
]
},
{
"post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics",
"authors": [
"https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
}
];
arr.forEach(post => post.authors[0] = post.authors[0].split('>')
.filter(item => !item.includes('https://www.agci.org'))
.join(','));
console.log(arr);

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>

How to make JavaScript Bingo generator not repeat same result?

I am trying to make a Thanksgiving Bingo generator and want to make it so the phrases appear only once.
Not sure what direction to take. Here is the code so far:
var questions = [
"Can name all 3 Pilgrim ships",
"Plays football",
"Has an unusual Thanksgiving tradition",
"Has a turkey disaster story",
"Vegetarian",
"Loves cranberry sauce",
"Has celebrated Thanksgiving in another country",
"Can name 5 things grateful for",
"Makes a mean green bean casserole",
"Eats mac and cheese on Thanksgiving",
"Has worked retail on Black Friday",
"Thanksgiving is favorite holiday",
"Has seen a turkey in real life",
"Watched the Macy's T-day parade in person",
"Willing to share pie recipe",
"Has attended a Friendsgiving",
"Loves leftovers",
"Dines out for Thanksgiving",
"Can name 5 native American tribes",
"Watches football",
"Can gobble like a turkey",
"Celebrates Canadian Thanksgiving",
"Hates cranberry sauce",
"Goes Black Friday shopping"
]
function newQuestion() {
var randomNumber = Math.floor(Math.random() * (questions.length));
document.getElementById('question-display').innerHTML = questions[randomNumber];
}
I think Shuffle and pop like #epascarello commented out is the perfect way in this case, here is an example:
var questions = [
"Can name all 3 Pilgrim ships",
"Plays football",
"Has an unusual Thanksgiving tradition",
"Has a turkey disaster story",
"Vegetarian",
"Loves cranberry sauce",
"Has celebrated Thanksgiving in another country",
"Can name 5 things grateful for",
"Makes a mean green bean casserole",
"Eats mac and cheese on Thanksgiving",
"Has worked retail on Black Friday",
"Thanksgiving is favorite holiday",
"Has seen a turkey in real life",
"Watched the Macy's T-day parade in person",
"Willing to share pie recipe",
"Has attended a Friendsgiving",
"Loves leftovers",
"Dines out for Thanksgiving",
"Can name 5 native American tribes",
"Watches football",
"Can gobble like a turkey",
"Celebrates Canadian Thanksgiving",
"Hates cranberry sauce",
"Goes Black Friday shopping"
].sort(_=> Math.random() - 0.5);
document.querySelector("#get-question").onclick = function() {
document.getElementById('question-display').innerHTML = questions.pop() || "There are no more questions!";
}
<p id="question-display"></p>
<button id="get-question">Get new question</button>

Map local .json data in React

I have a local .json file formated below
{
"results": [
{
"id": 1,
"title": "2 bedroom apartment to rent",
"location": "30 South Colonnade London E14 5EZ",
"description": "The building offers a communal lifestyle which consists of a large lounge area with dining room, working space, TV lounge, gym, stylish meeting rooms, free table tennis, free WIFI and a spacious communal roof terrace. Local transport includes Canning Town DLR and Jubilee Line (0.1 miles). Argo Apartments is managed by Grainger plc, one of the UK's leading professional landlords with over 100 years experience.",
"price": "1,800",
"beds": 2,
"bathrooms": 1,
"landlord": "Hamptons International Lettings",
"images": ["image1", "image2"]
},
{
"id": 2,
"title": "2 bedroom flat to rent",
"location": "Textile Building, Chatham Place, Hackney, London, E9",
"description": "SHORT LET - Forming part of the new eagerly awaited Textile Building in Hackney Central E8, this stunning two double bedroom property has been finished to the highest standard, featuring two modern fitted bathrooms (one en-suite), two equal double bedrooms, spacious open plan reception with brand new integrated kitchen, exposed brickwork and communal underground bike storage.",
"price": "2,400",
"beds": 2,
"bathrooms": 1,
"landlord": "Stirling Ackroyd, Hackney",
"images": ["image1", "image2"]
},
{
"id": 3,
"title": "3 bedroom apartment to rent",
"location": "Sixth Floor Tower Building 11 York Road London SE1 7NX",
"description": "A fantastic three bedroom apartment set in this popular development close to Vauxhall and Stockwell tube stations. The apartment is neutrally decorated throughout and is available either furnished or unfurnished. Residents will enjoy the plethora of shops, bars and restaurants and leisure activities in this popular part of London as well as the excellent commuter links towards Central London.",
"price": "2,050",
"beds": 3,
"bathrooms": 2,
"landlord": "Regent Letting and Property Management",
"images": ["image1", "image2"]
}
],
"newResults" : [
{
"id": 4,
"title": "2 bedroom flat to rent",
"location": "Conway Street, Fitzrovia, W1T",
"description": "Complete is delighted to market this newly renovated period property situated on the corner of Fitzroy Square in the heart of Fitzrovia, W1. The property is located on the ground floor and comes with 2 double bedrooms, shower room, open plan living and kitchen area. The kitchen is fully fitted with Siemens appliances and Duravit fittings in the bathroom. This apartment has high ceiling and retains its original period features. Located on the corner of this garden square this development was built in the 18th Century and benefits from being in the heart of vibrant London whilst also being a quiet residential area.",
"price": "1,500",
"beds": 2,
"bathrooms": 1,
"landlord": "Barnard Marcus Lettings",
"images": ["image1", "image2"]
}
]
}
I want to be able to call the relevent information mapped to a component as below
class ResultsLists extends React.Component {
constructor(props) {
super(props)
this.state = {
results: resultsData
}
}
render() {
const results = this.state.results.results.map((result) =>
<li>{result}</li>
);
return (
<div className="rst-List">
<ul className="rst-List_Items">
{results}
</ul>
</div>
)
}
}
I can't seem to get it too work and am getting the error - Objects are not valid as a React child. There seems to be a varying variety as to why this isn't working, wondered whether someone could sanity check.
You're mapping over the results, but then you're putting the whole result object into the JSX.
This is an example of how to map over data:
const someData = [{ name: "Colin" }, { name: "Ricardo" }];
const App = () => {
const temp = someData.map(o => <li>{o.name}</li>);
return (
<div>
<ul>{temp}</ul>
</div>
);
};
Note that we have {o.name} and not just {o}.
Working example here.
So in your case, you need something like:
const results = this.state.results.results.map((result) =>
<li>{result.title}</li>
);

Javascript object property not multiline

I am using a object in Javascript to store recipes and cannot get the "process" property to show as multiline. This has to be easy but not working. I am rendering the data as a tag in react.js.
let recipes = [
{
id:1,
dish: "Chicken and Rice",
ingredients: "Left over chicken",
process: "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling."
},
{
id:2,
dish: "Beef and Rice",
ingredients: "Left over beef",
process: "1)Chop up chicken in bite sized chunks <br> 2)Heat 1 Tablespoon olive oil in your favorite pan 3) Dice any veggies in your pantry and add these and chicken to pan and heat through optional: Mix with fresh rice or quinoa to make more filling."
},
{
id:3,
dish: "Rice and Rice",
ingredients: "Left over beef",
}
]
export default recipes;
You can split up the string on \n and map each line to an element.
render: function() {
let process = "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling.";
let lines = process.split("\n");
let mappedLines = lines.map((line)=>{
return <p>{line}</p>
});
return <div>{mappedLines}</div>;
}
https://jsfiddle.net/69z2wepo/82459/

Categories

Resources