Using Arrays in JS - javascript

So i'm trying to make a page that will pull out a fact from an array and print it out.
var fact = [
{
id: 1,
fact: "Cutis Anserina is the medical term for goosebumps.",
question: "What common occurence is Cutis Anserina the medical term for?"
option1: "Goosebumps",
option2: "Hiccups",
option3: "Laughter",
option4: "Sneezing",
correct: option1
},
{
id: 2,
fact: "The famous nursery rhyme,“Ringa Ringa Roses”, was actually based on the Black Death.",
question: "What historical event is “Ringa Ringa Roses” based on?",
option1: "The Great Depression",
option2: "American Civil War",
option3: "The Black Death",
option4: "Indian Independence Struggle",
correct: option3
},
{
id: 3,
fact: "Gobind Behari Lal is the first Indian to have won the famed Pulitzer Prize for Literature",
question: "Who is the first Indian to win the Pulitzer Price?",
option1: "Vijay Seshadri",
option2: "Gobind Behari Lal",
option3: "Jhumpa Lahiri",
option4: "Dr. Siddhartha Mukherjee",
correct: option2
},
{
id: 4,
fact: "OVI Intaglio is an ink from Swiss firm SLCPA and is used in the printing of watermark on Indian currency notes",
question: "What ink is used to print the watermark on Indian currency notes?",
option1: "OVI Intaglio",
option2: "Parker Supreme",
option3: "Bril Blue",
option4: "L'ink special",
correct: option1
},
{
id: 5,
fact: "The inhabitants of the planet Earth are called Tellurians",
question: "The inhabitants of which planet are known as Tellurians?",
option1: "Saturn",
option2: "Jupiter",
option3: "Mars",
option4: "Earth",
correct: option4
},
];
i need the program to take out only the fact when id="1", "2" etc. This page is supposed to pull out only the data marked as "fact" from array for the respective ids. Please tell me what i can add or remove
Please help :(

Related

Access data from JSON objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I have this code in js with data from a series and I would like to access only some data, such as name, number of episodes, summary, etc. To put in a box, which is in html. However, when making the JSON code (at the end) in text format (and it should be that way), the code is limited to printing just one piece of information (let text = JSON.stringify(bd.name,bd.resumo,bd.note );),this is i tried. How can I make it print more than one information I want inside the html box?
const db = {
name: "Stranger Things",
genera: [
"Mystery",
"Sci-Fi & Fantasy",
"Drama"
],
num_episodes: 25,
season_num: 3,
grade: 8.5,
summary: "When a boy disappears, the whole city participates in the search. But what they find are secrets, supernatural forces and a girl.",
cast: [
{
name: "Winona Ryder",
character: "Joyce Byers",
},
{
name: "David Harbour",
character: "Jim Hopper",
},
{
name: "Finn Wolfhard",
character: "Mike Wheeler",
},
{
name: "Millie Bobby Brown",
character: "Eleven",
},
{
name: "Gaten Matarazzo",
character: "Dustin Henderson",
},
{
name: "Caleb McLaughlin",
character: "Lucas Sinclair",
},
{
name: "Natalia Dyer",
character: "Nancy Wheeler",
},
{
name: "Charlie Heaton",
character: "Jonathan Byers",
},
{
name: "Sadie Sink",
character: "Max Mayfield",
},
{
name: "Dacre Montgomery",
character: "Billy Hargrove",
},
{
name: "Dear Buono",
character: "Karen Wheeler",
},
{
name: "Noah Schnapp",
character: "Will Byers",
},
{
name: "Joe Keery",
character: "Steve Harrington",
},
{
name: "Priah Ferguson",
character: "Erica Sinclair",
},
{
name: "Maya Hawke",
character: "Robin",
}
],
seasons: [
{
number 1,
number_episodes: 8,
display: "2016-07-15",
summary: "The small town of Hawkins is the scene of strange events. After the disappearance of a boy, a girl appears with supernatural powers.",
episodes: [
{
number 1,
name: "Chapter One: The Disappearance of Will Byers",
grade: 7.79,
summary: "On his way home, Will is terrified of something. Not far away, a secret laboratory holds a sinister secret."
},
{
number 2,
name: "Chapter Two: The Maple Street Stranger",
grade: 8,194,
summary: "Lucas, Mike, and Dustin try to talk to the girl they meet. Hopper has questions for an extremely anxious Joyce."
},
{
number: 3,
name: "Chapter Three: Dammit",
grade: 8,634,
summary: "Increasingly worried, Nancy seeks out Barb and finds out what Jonathan has been up to. Joyce is convinced that Will is trying to communicate with her."
},
{
number 4,
name: "Chapter Four: The Body",
grade: 8,341,
summary: "Joyce refuses to believe Will died, and tries to communicate with him. The boys transform Eleven's look. Nancy and Jonathan end up teaming up."
},
{
number 5,
name: "Chapter Five: The Flea and the Acrobat",
grade: 8.16,
summary: "Hopper manages to enter the lab while Nancy and Jonathan confront the forces that took Will away. The boys ask Mr. Clarke how he goes to another dimension."
},
{
number: 6,
name: "Chapter Six: The Monster",
grade: 8,371,
summary: "Desperate, Jonathan searches for Nancy in the dark, but Steve does the same thing. Hopper and Joyce discover the truth about the experiments conducted in the lab."
},
{
number: 7,
Name: "Chapter Seven: The Bathtub",
grade: 8,233,
summary: "Eleven tries to reach Will, but Lucas gives the danger alert. Nancy and Jonathan show the police the images captured by the camera."
},
{
number: 8,
name: "Chapter eight: Upside down",
grade: 8,437,
summary: "Dr. Brenner interrogates Hopper and Joyce while the boys and Eleven wait in the gym. Nancy and Jonathan prepare for a new battle."
}
]
},
{
number 2,
number_episodes: 9,
display: "2017-10-27",
summary: "Almost a year after Will's strange disappearance, life in Hawkins is far from returning to normal.",
episodes: [
{
number 1,
name: "Chapter One: Mad Max",
grade: 7,894,
summary: "On Halloween eve, a rival messes things up in the arcade. Skeptical, Hopper inspects a field of rotting pumpkins."
},
{
number 2,
name: "Chapter Two: Trick or Treat, Freak",
grade: 8,018,
summary: "After Will sees something terrible on trick-or-treating night, Mike wonders if Eleven is still around. Nancy faces the truth about Barb's death."
},
{
number: 3,
name: "Chapter Three: The Tadpole",
grade: 8,
summary: "Dustin adopts a strange pet, and Eleven grows more and more impatient. Well-meaning, Bob encourages Will to face his fears."
},
{
number 4,
name: "Chapter Four: Will the Sage",
grade: 8,241,
summary: "Weakened, Will opens up to Joice, and the result is disturbing. While Hopper searches for the truth, Eleven makes a startling discovery."
},
{
number 5,
name: "Chapter Five: Dig Dug",
grade: 8,196,
summary: "Nancy and Jonathan exchange conspiracy theories with a new ally, and Eleven is looking for someone from her past. 'Smart Bob' deals with a tricky problem."
},
{
number: 6,
name: "Chapter Six: The Spy",
grade: 8,386,
summary: "The link between Will and a sinister evil force grows stronger, but no one is quite sure how to stop it. Dustin and Steve create an unlikely bond."
},
{
number: 7,
name: "Chapter Seven: The Lost Sister",
grade: 6918,
summary: "Psychic visitors drag Eleven toward a group of violent outcasts and an angry girl with a dark past."
},
{
number: 8,
name: "Chapter Eight: The Mind Flayer",
grade: 8,417,
summary: "An unlikely hero arises when a deadly incident causes the Hawkins Laboratory to close, leaving Will and several others trapped inside."
},
{
number: 9,
name: "Chapter Nine: The Portal",
grade: 8,345,
summary: "Eleven plans to finish what he started. The survivors increase the pressure against the monstrous force that holds Will hostage."
}
]
},
{
number: 3,
number_episodes: 8,
display: "2019-07-04",
summary: "Novel in the air. A brand-new mall. Crazed rats running into danger. It's the summer of 1985 in Hawkins. And one summer can change everything.",
episodes: [
{
number 1,
name: "Chapter One: Are You Listening to Me, Suzie?",
grade: 7,511,
summary: "Summer is a time for temp jobs and new dating. But the mood changes when Will notices something is wrong with Dustin's radio broadcast in Russian."
},
{
number 2,
name: "Chapter Two: The Case of the Rats",
grade: 7,806,
summary: "Nancy and Jonathan follow a a clue. Steve and Robin participate in a secret mission, and Max and Eleven go shopping. Billy has disturbing visions."
},
{
number: 3,
name: "Chapter Three: The Missing Lifeguard",
grade: 7,926,
summary: "Eleven and Max are looking for Billy. Will plans a day without the girls. Steve and Dustin ambush, and Joyce and Hopper return to Hawkins National Laboratory."
},
{
number 4,
name: "Chapter Four: The Proof of the Sauna",
grade: 8,414,
summary: "The gang gathers to face a terribly familiar evil. Karen asks Nancy to continue the investigation. Robin gets a very useful mall blueprint."
},
{
number 5,
name: "Chapter Five: The Devoured",
grade: 7,769,
summary: "Strange surprises lurk in an old farm and in the depths of the Starcourt Mall. The Mind Flayer grows stronger."
},
{
number: 6,
name: "Chapter Six: E Pluribus Unum",
grade: 7,963,
summary: "Dr. Alexey reveals what the Russians are building, and Eleven sees where Billy has been. Dustin and Erica plan a daring rescue."
},
{
number: 7,
name: "Chapter Seven: The Bite",
grade: 8,
summary: "With time running out and an assassin drawing nearer, Hopper's team races back to Hawkins. There, Eleven and the rest of the gang prepare for war."
},
{
number: 8,
name: "Chapter Eight: The Battle of Starcourt",
grade: 8.8,
summary: "The Mind Flayer causes terror in the food court. Down below, in the darkness, the future of humanity is at stake."
}
]
}
]
}
const box = document.querySelector('#box');
let text = JSON.stringify(db.name,db.summary,db.note);
box.innerText = text;
let object = JSON.parse(text);
console.log(object);
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Objetos</title>
<style>
#box{
padding: 1em;
border: 2px solid #333;
}
</style>
</head>
<body>
<div id = "box"></div>
<script type="text/javascript" src="db.js"></script>
</body>
</html>
let text = JSON.stringify(db.name,db.summary,db.note);
this line of code is only returning the db.name, db.summary, and db.note
to access more info you can just get all of the data back (db) or if you want to use something more specific you can type db.seasons.summary and it will return all of the seasons summaries. Also your going to need to use fetch() to get that data

Finding Data from a Json Array Using JavaScript

I have JSON data that is structured like this
[
{
"cs": [
{
"dr": "(i) Two passes at 'A' level in Biology /Zoology /Botany and any other Science subject. (ii) NCE at merit pass level in Biology and any other Science subject. (iii) NCE merit pass level in Agriculture (Double Major).",
"ur": "Five SSCE credits or equivalent in English Language, Chemistry, Biology/Agricultural Science., Mathematics and another relevant subject.",
"us": "Any three subjects from Chemistry, Biology, Agriculture, Physics, Economics, Geography and Mathematics.",
"dc": "BAUCHI accepts: (a) NCE (pass with 5 years teaching experience. (b) N.D at merit pass/lower credit in Biology/Agricultural Science and any other Science subject. (c) Two 'A' Level passes in Biology /Zoology/Botany/Agricultural Science and any other Science subject.",
"uc": "BAUCHI requires Five 'O' level credit passes in English, Mathematics, Arithmetic, Biology, Agricultural Science, Chemistry or General Science and any two subjects. It accepts credit pass in Arithmetic, or General Science or Technical Trades in lieu of Mathematics, or Biology or Physics respectively. UTME SUBJECTS:|BAUCHI requires Mathematics, Biology/Agricultural Science and any other subject.",
"_n": "Agricultural Science And Education",
"_c1": "96",
"_c2": "81",
"_c3": "30",
"_c4": "0",
"_t": "207"
}
...
],
"_n": "Abubakar Tafawa Balewa University, Bauchi",
"_no": "55",
"_c1": "10332",
"_c2": "632",
"_c3": "226",
"_c4": "1",
"_t": "11191",
"_own": "FEDERAL",
"_ab": "BAUCHI",
"_st": "BAUCHI",
"_em": "",
"_pn": "",
"_ws": "atbu.edu.ng",
"_ca": "ADAMAWA, BAUCHI, BENUE, BORNO, GOMBE, TARABA, YOBE"
},
{
"cs": [
{
"dr": "Two A' Level passes in Economics, Accountancy, Business Management, Government and Geography. Candidate must have Science background at 'O' Level.",
"ur": "Five SSCE credit passes to include, English Language, Mathematics, Economics and any other two science subjects from Chemistry, Physics, Biology, Geography, Health Science, Metal Works, Wood Work, Agric Science, Technical Drawing, Nutrition and Food Science.",
"us": "Mathematics, Economics and any one of Chemistry, Physics or Biology.",
"dc": "BAUCHI accepts: (a) Two 'A' level passes in any of Math, Economics, Commerce, Physics, Chemistry, Bio/Agric. (b) ND/HND at lower credit and above.",
"uc": "BAUCHI requires five 'O' level credit passes to include English Language, Mathematics, one Science subject and two Commercial subjects.",
"_n": "Accounting Technology",
"_c1": "490",
"_c2": "19",
"_c3": "8",
"_c4": "0",
"_t": "517"
},
...
],
"_n": "University of Lagos",
"_no": "55",
"_c1": "10332",
"_c2": "632",
"_c3": "226",
"_c4": "1",
"_t": "11191",
"_own": "FEDERAL",
"_ab": "BAUCHI",
"_st": "BAUCHI",
"_em": "",
"_pn": "",
"_ws": "unilag.edu.ng",
"_ca": "ADAMAWA, BAUCHI, BENUE, BORNO, GOMBE, TARABA, YOBE"
}
...
]
i want to search the JSON array using the name of the using a course say "Agricultural Science And Education" then it should the university in this case "University of lagos" and "Abubakar Tafawa Balewa University, Bauchi" and the _ur (requirement)
In your example University of lagos doesn't have a Agricultural Science And Education, try this:
for(let i = 0; i < arr.length; i++){
if(Object.values(arr[i]['cs'][0]).includes('Agricultural Science And Education')){
console.log(arr[i]['_n'])
}
}

Adding Images to Objects

I am working on a project where we I have an array full of objects. It stores movie information, and I would like to add an image of the poster onto the object as well. Below is an example of my code. I have functions that searches through the array for specific movies based on given information, and returns the information. I would like it to return an image with it as well. This information then gets printed onto a website. Here is the code:
var allMovies = [
{
Title: "Green Book",
Year: 2019,
Director: "Peter Farrelly",
Winner: "yes",
Genre: "Biography, Comedy, Drama"
},
{
Title: "Black Panther",
Year: 2019,
Director: "Ryan Coogler",
Winner: "no",
Genre: "Action, Sci-Fi"
},
and there is more code after this, but it is too long to add the whole code. Is there a way to add an image, and have it be returned with this information, and then be printed onto a page?
Similar to what #rid said, but ill add a bit more, maybe it will help.
so your array is:
var allMovies = [
{
Title: "Green Book",
Year: 2019,
Director: "Peter Farrelly",
Winner: "yes",
Genre: "Biography, Comedy, Drama",
Image:"https:website.com/images/image.jpg"
},
{
Title: "Black Panther",
Year: 2019,
Director: "Ryan Coogler",
Winner: "no",
Genre: "Action, Sci-Fi",
Image:"https:website.com/images/image.jpg"
}
]
Now you can loop through the array and use template literals to create your HTML output, it could be done like this:
let output='';
allMovies.forEach(Movie=>{
//we use template literals here to make things easier
output+=`<h1>Title: ${Movie.Title}</h1>
<img src="${Movie.Image}" alt="Movie Image">
<p>Year: ${Movie.Year}<p>
<p>Director: ${Movie.Director}</p>
<p>Winner: ${Movie.Winner}</p>
<p>Genre: ${Movie.Genre}</p>
`
})
const div =document.querySelector("yourdiv");
div.innerHTML=output;
I hope this helped :)
You have to add the url of the image.
Like this,
var allMovies = [
{
Title: "Green Book",
Year: 2019,
Director: "Peter Farrelly",
Winner: "yes",
Genre: "Biography, Comedy, Drama",
Image_url: "https://www.something.com/something/something.jpg"
},
{
Title: "Black Panther",
Year: 2019,
Director: "Ryan Coogler",
Winner: "no", Genre: "Action, Sci-Fi",
Image_url: "https://www.something.com/something/something.jpg"
},

I'm trying to create an array of results from my return on an AJAX call. How do I do that?

I'm trying to create a list (not a ) of results from an AJAX call/return. I think there's something missing for my "for loop" to work. I'm getting the results in my console.log but most of the results are missing on the webpage I'm creating. (My URL is good, etc. Even have the necessary "cors" URL.)
These are my results showing in the console.log:
{trails: Array(10), success: 1}
success: 1
trails: Array(10)
0: {id: 7003421, name: "Mount Helena Ridge Trail", type: "Trail", summary: "Follows the Mount Helena ridgeline from Prosepector Gulch to the Mount Helena City Park trails.", difficulty: "greenBlue", …}
1: {id: 7004967, name: "Emmett's Trail", type: "Trail", summary: "A nice forested and shaded option for climbing up to the Mt. Helena Ridge Trail from Grizzly Gulch.", difficulty: "blueBlack", …}
2: {id: 7004981, name: "Mt Ascension Loop", type: "Trail", summary: "A partial loop trail that follows the north side of Mt Ascension and loops around to the south side.", difficulty: "blue", …}
3: {id: 7004847, name: "Stairway to Heaven", type: "Trail", summary: "A short trail climbing at first, then dropping through short switchbacks to connect to Wakina Gulch.", difficulty: "blue", …}
4: {id: 7004852, name: "Wakina Sky Trail", type: "Trail", summary: "A trail that climbs through forest and then into a meadow and forms a beautiful 2+ mile loop.", difficulty: "blue", …}
5: {id: 7004842, name: "Entertainment Trail", type: "Trail", summary: "A beautiful trail climbing Mt. Ascension with great views of the surrounding mountains.", difficulty: "blueBlack", …}
6: {id: 7005245, name: "Archery Range Trail", type: "Trail", summary: "A flat trail that hugs the contours of Mt. Ascension.", difficulty: "greenBlue", …}
7: {id: 7004841, name: "Eagle Scout Trail", type: "Trail", summary: "A short ascent taking you to the Mt Ascension trail system.", difficulty: "blueBlack", …}
8: {id: 7005001, name: "Rodney Meadow Trail", type: "Trail", summary: "A short climb and then a nice flat trail through a meadow with views.", difficulty: "blue", …}
9: {id: 7004980, name: "2006 Trail", type: "Trail", summary: "A climbing switchback trail up the north side of Mt Ascension.", difficulty: "blue", …}
length: 10
url: hikeQueryURL,
method: "GET"
}).then(function(hikeResponse) {
// Printing the entire object to console
console.log(hikeResponse);
for(i = 0; i < trails.length; i++) {
// Constructing HTML containing the trail information
var hikeName = $("<h1>").text(hikeResponse.trails.name);
var hikeImage = $("<img>").attr("src", hikeResponse.trails.imgSqSmall);
var hikeSummary = $("<p>").text(hikeResponse.trails.summary);
var hikeLength = $("<h2>").text("Trail length: " + hikeResponse.trails.length);
var hikeCondition = $("<p>").text("Current Trail Conditions: " + hikeResponse.trails.conditionStatus + ": " + hikeResponse.trails.conditionDetails);
// Empty the contents of the "hiking-info" div, append the new trail content
$("#hiking-info").empty();
$("#hiking-info").append(hikeName, hikeImage, hikeSummary, hikeLength, hikeCondition);
};
});```
I'm just expecting all of the info from the AJAX return to be put into my variables, then appended into my empty "hiking-info" div.
First of all, you are iterating trough the JSON response with a FOR loop, but it's missing the index in all keys.
Second, your FOR loop condition is wrong, you are using the wrong object.
And last, you are saving values in your variables, then EMPTYING the div, and then putting those variables in the div, thus clearing all content in the div after each iteration (this is, showing only the last iteration in the div)
You may try with this corrections:
for(i = 0; i < hikeResponse.trails.length; i++) {
// Constructing HTML containing the trail information
var hikeName = $("<h1>").text(hikeResponse.trails[i].name);
var hikeImage = $("<img>").attr("src", hikeResponse.trails[i].imgSqSmall);
var hikeSummary = $("<p>").text(hikeResponse.trails[i].summary);
var hikeLength = $("<h2>").text("Trail length: " + hikeResponse.trails[i].length);
var hikeCondition = $("<p>").text("Current Trail Conditions: " + hikeResponse.trails[i].conditionStatus + ": " + hikeResponse.trails[i].conditionDetails);
// no need for empty the div
//$("#hiking-info").empty();
$("#hiking-info").append(hikeName, hikeImage, hikeSummary, hikeLength, hikeCondition);
};

What is the correct type of Javascript array to use when building a questionnaire? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm building a single-page questionnaire app and I'm not sure what is the correct way to build my arrays for the questions. Also, is it bad practice to mix types of questions in this manner? (Single choice, multi-choice in same array?) Basically, I'm still trying to understand the advantages/disadvantages of the two basic approaches I've seen.
Option 1:
var hygiene = [
{
pageheader: "Self-Care"
}
{
q: "When was your last shower?",
choicetype: "radio",
a1: "Today",
a2: "Yesterday",
a3: "Two days ago",
a4: "I don't know"
}
{
q: "How much do you weigh today?",
choicetype: "keypad"
}
{
q: "Do you take any medications?",
choicetype: "radio",
a1: "Yes",
a2: "No"
}
{
q: "Which medications?",
choicetype: "multiselect",
a1: "Zostavax",
a2: "Percocet",
a3: "Actemra",
a4: "Cimzia",
a5: "Relprevv"
}
];
Option 2:
var hygiene = {
pageheader: "Self-Care",
question1: [
"When was your last shower?", "radio", "Today", "Yesterday",
"Two days ago", "I don't know"
],
question2: [
"How much do you weigh today?", "keypad"
],
question3: [
"Do you take any medications?", "radio", "Yes", "No"
],
question4: [
"Which medications?", "multiselect", "Zostavax", "Percocet",
"Actemra", "Cimzia", "Relprevv"
]
};
My recommendation is not to use either of them, but the following:
var hygiene = {
pageheader: "Self-Care",
questions: [
{
question: "When was your last shower?",
choicetype: "radio",
answers: [
"Today",
"Yesterday",
"Two days ago",
"I don't know"
]
},
{
question: "How much do you weigh today?",
choicetype: "keypad"
},
{
question: "Do you take any medications?",
choicetype: "radio",
answers: [
"Yes",
"No"
]
},
{
question: "Which medications?",
choicetype: "multiselect",
answers: [
"Zostavax",
"Percocet",
"Actemra",
"Cimzia",
"Relprevv"
]
}
]
}
Option 1 is much better than option 2, because you specify the variables and gave each of the string meaningful names to be used later in your code.
It depends on the readability of your code later if you had a large chunk of questionaires. If you had 100 of these in a file, would you prefer 1 or 2?

Categories