How to implement a 'contains' search in JavaScript - 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>
Related
How can I generate a random selection based on user's <select> option choice?
I am trying to have a user select a genre from my drop down list and get a random result from the genre they selected that is then displayed on the screen. In other words, my idea is to have a user get a random options from the genre they choose from my list. I am very very new to JavaScript but I want to try to do something creative for my project. I have tried this so far function xyz() { var x = document.getElementById("selectedId").value; if (x == "action") { var action = ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"] var result = Math.floor(Math.random() * action.length); console.log(action); } else if (x == "comedy ") { var comedy = ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"] var result = Math.floor(Math.random() * comedy.length); console.log(comedy); } else if (x == "drama") { var drama = ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"] var result = Math.floor(Math.random() * drama.length); console.log(drama); } else if (x == "sliceofLife") { var sliceofLife = ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"] var result = Math.floor(Math.random() * sliceofLife.length); console.log(sliceofLife); } else if (x == "fantasy") { var fantasy = ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"] var result = Math.floor(Math.random() * fantasy.length); console.log(fantasy); } else if (x == "horror") { var horror = ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"] var result = Math.floor(Math.random() * horror.length); console.log(horror); } else if (x == "mystery") { var mystery = ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"] var result = Math.floor(Math.random() * mystery.length); console.log(mystery); } else if (x == "psychological") { var psychological = ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"]; var result = Math.floor(Math.random() * psychological.length); console.log(psychological); } else { var boysLove = ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"] var result = Math.floor(Math.random() * boysLove.length); console.log(boysLove); } } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--Language encoding--> <meta name="viewport" content="width=device-width, initial-scale=1.0>" <title> Final Project </title> <link rel="stylesheet" type="text/css" href="FPCSS.css" /> </head> <body class="style"> <div id="Top"> <p class="title"> Anime for All <IMG class="IMG1" SRC="five.gif"> </p> <p> <br> </p> <div class="Directory"> <!-- Website navigation--> <h1>Directory</h1> <p> Homepage</p> <p> Anime History</p> <p> Misconceptions and Genres</p> <p> Recommendations</p> <p> Random Anime Generator</p> <p>Email me!</p> </div> <div class="MS"> <!--MS= format for main section--> <h1>Random Anime Generator</h1> <label> Select your Favorite genres to generate a anime!</label> <select id="selectedId"> <option>Choose a Genre</option> <option value="action"> Action</option> <option value="adventure">Adventure</option> <option value="comedy">Comedy</option> <option value="drama">Drama</option> <option value="sliceOfLife">Slice Of Life</option> <option value="fantsy">Fantsy</option> <option value="horror">Horror</option> <option value="mystery">Mystery</option> <option value="psychological">Psychological</option> </select> <p> Your random anime based on chosen genre is....</p> <p id="result"> </p> <script src="Final_Project_JS.js"></script> </div> </div>
You could store all full list of anime titles in a variable—preferably an object of arrays. Whenever user selects a genre, you could simply generate a random integer per each sublist's length and show the result in the target p element. See the snippet below for working example. I didn't modify the original HTML markup too much, except removing irrelevant elements to the question. For this to work as intended, you need to make sure the list of option values match the keys of titles object. const titles = { action: ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"], comedy: ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"], drama: ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"], sliceOfLife: ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"], fantasy: ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"], horror: ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"], mystery: ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"], psychological: ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"], boysLove: ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"] } const selectionHandler = e => { const genre = e.target.value; const targetList = titles[genre]; if (!targetList) { result.innerText = "No anime found"; } else { const randomIndex = Math.floor(Math.random() * targetList.length); result.innerText = targetList[randomIndex]; } } const input = document.querySelector('#selectedId'); const result = document.querySelector('#result'); input.addEventListener('change', selectionHandler); #result { padding: 10px; background: #eee; display: inline-block; } <div id="Top"> <p class="title"> Anime for All</p> <div class="MS"> <!--MS= format for main section--> <h1>Random Anime Generator</h1> <label> Select your Favorite genres to generate a anime!</label> <select id="selectedId"> <option>Choose a Genre</option> <option value="action"> Action</option> <option value="adventure">Adventure</option> <option value="comedy">Comedy</option> <option value="drama">Drama</option> <option value="sliceOfLife">Slice Of Life</option> <option value="fantasy">Fantsy</option> <option value="horror">Horror</option> <option value="mystery">Mystery</option> <option value="psychological">Psychological</option> </select> <p> Your random anime based on chosen genre is....</p> <p id="result"></p> </div> </div>
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 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>
Can't parse a JSON file
I started learning node.js and I am facing an error. Here's the code: const server = http.createServer((req, res) =>{ //request, response const pathName = req.url; if (pathName === '/' || pathName === '/overview'){ res.end('This is the OVERVIEW') // res trimite catre client, req trimite catre server } else if (pathName === '/product'){ res.end('This is the PRODUCT'); } else if (pathName === '/api') { fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => { const productData = JSON.parse(data); response.writeHead(200, { 'Content-type': 'application/json' }); response.end(data); }); } else{ res.writeHead(404, { 'Content-type': 'text/html', 'my-own-header': 'hello-world' }); res.end('<h1>This page could not be found!</h1>'); } res.end('Hello from the server!'); }); the problem is in this if: else if (pathName === '/api') { fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => { const productData = JSON.parse(data); response.writeHead(200, { 'Content-type': 'application/json' }); response.end(data); }); The error i get: undefined:1 undefined ^ SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at ReadFileContext.callback (c:\Users\40721\Desktop\nodeJs&Express\complete-node-bootcamp-master\1-node-farm\index.js:49:38) at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13) The data.json file i want to read from is this: [ { "id": 0, "productName": "Fresh Avocados", "image": "🥑", "from": "Spain", "nutrients": "Vitamin B, Vitamin K", "quantity": "4 🥑", "price": "6.50", "organic": true, "description": "A ripe avocado yields to gentle pressure when held in the palm of the hand and squeezed. The fruit is not sweet, but distinctly and subtly flavored, with smooth texture. The avocado is popular in vegetarian cuisine as a substitute for meats in sandwiches and salads because of its high fat content. Generally, avocado is served raw, though some cultivars, including the common 'Hass', can be cooked for a short time without becoming bitter. It is used as the base for the Mexican dip known as guacamole, as well as a spread on corn tortillas or toast, served with spices." }, { "id": 1, "productName": "Goat and Sheep Cheese", "image": "🧀", "from": "Portugal", "nutrients": "Vitamin A, Calcium", "quantity": "250g", "price": "5.00", "organic": false, "description": "Creamy and distinct in flavor, goat cheese is a dairy product enjoyed around the world. Goat cheese comes in a wide variety of flavors and textures, from soft and spreadable fresh cheese to salty, crumbly aged cheese. Although it’s made using the same coagulation and separation process as cheese made from cow’s milk, goat cheese differs in nutrient content." }, { "id": 2, "productName": "Apollo Broccoli", "image": "🥦", "from": "Portugal", "nutrients": "Vitamin C, Vitamin K", "quantity": "3 🥦", "price": "5.50", "organic": true, "description": "Broccoli is known to be a hearty and tasty vegetable which is rich in dozens of nutrients. It is said to pack the most nutritional punch of any vegetable. When we think about green vegetables to include in our diet, broccoli is one of the foremost veggies to come to our mind. Broccoli is a cruciferous vegetable and part of the cabbage family, which includes vegetables such as Brussel sprouts and kale. Although the tastes are different, broccoli and these other vegetables are from the same family." }, { "id": 3, "productName": "Baby Carrots", "image": "🥕", "from": "France", "nutrients": "Vitamin A, Vitamin K", "quantity": "20 🥕", "price": "3.00", "organic": true, "description": "The carrot is a root vegetable that is often claimed to be the perfect health food. It is crunchy, tasty and highly nutritious. Carrots are a particularly good source of beta-carotene, fiber, vitamin K, potassium and antioxidants. Carrots have a number of health benefits. They are a weight loss friendly food and have been linked to lower cholesterol levels and improved eye health." }, { "id": 4, "productName": "Sweet Corncobs", "image": "🌽", "from": "Germany", "nutrients": "Vitamin C, Magnesium", "quantity": "2 🌽", "price": "2.00", "organic": false, "description": "Also known as maize, corn is one of the most popular cereal grains in the world. Popcorn and sweet corn are commonly eaten varieties, but refined corn products are also widely consumed, frequently as ingredients in foods. These include tortillas, tortilla chips, polenta, cornmeal, corn flour, corn syrup, and corn oil. Whole-grain corn is as healthy as any cereal grain, rich in fiber and many vitamins, minerals, and antioxidants." } ]
Are you storing the image property as a location to the image? JSON only accepts these datatypes: a string a number an object (JSON object) an array a boolean null
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> );