Access data from JSON objects [duplicate] - javascript

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

Related

Getting only needed elements form array in MongoDb Schema

I want to get only those element from notes Array that match the given tag from tags array in notes.
For example : If I want to get only those notes from notes Array having lrn tag in tags array but I am getting either the whole object or only the first matching note.
My Schema :
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
user : {
type: String,
required: true,
unique : true
},
notes : {
type : [{
title : {
type: String,
required: true
},
tags : {
type : [String],
required: true
},
note: {
type: String,
required: true
}
}],
required: true
}
});
const Notebook = mongoose.model('NOTEBOOK', noteSchema);
module.exports = Notebook;
My sample data :
{ _id: ObjectId("621c3a41fa2fe3c07f43edc9"),
user: '620c81434d8a65c1aa36e0d4',
notes:
[ { title: 'Eraning',
tags: [ 'ern', 'lrn', 'dik', 'pik', 'sik' ],
note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\nPrior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\n',
_id: ObjectId("62205a32bab7aed6315195e9") },
{ title: 'Lerningngs',
tags: [ 'lrn', 'eat', 'drink' ],
note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\n',
_id: ObjectId("6220583cbab7aed63151958b") },
{ title: 'Learning',
tags: [ 'learn', 'eran', 'buy', 'sell' ],
note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.\n',
_id: ObjectId("6220532dbab7aed631519531") },
{ title: 'Biology',
tags: [ 'tissue', 'cell', 'myto', 'energy', 'glycogen', 'hydrogen' ],
note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.\n\n',
_id: ObjectId("621f88d4c189c6b5501c3d5f") },
{ title: 'Chemistry',
tags: [ 'this', 'is', 'great', 'thing', 'to', 'do', 'by', 'time' ],
note: ' Prior to his return, Craig worked at NeXT, followed by Apple, \n and then spent a decade at Ariba, an internet e-commerce pioneer \n where he held several roles including chief technology officer.\n',
_id: ObjectId("621f85e9c189c6b5501c3d49") },
{ title: 'Physics',
tags:
[ 'newtonlawsofmotion',
'ktg',
'thermo',
'fluid',
'mechanice',
'bernaulii' ],
note: 'P\' + hrg + 1/2rv^2 = constant',
_id: ObjectId("621f8520c189c6b5501c3d3f") },
{ title: 'Maths',
tags: [ 'trignometry', 'llp', 'continuity', 'tags', 'circle' ],
note: 'Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.',
_id: ObjectId("621f84d7c189c6b5501c3d37") },
{ title: 'DSA from Net',
tags: [ 'dp', 'stack', 'queue', 'heaps', 'sorting' ],
note: 'Solving DSA from Leetcode.in and GeeksforGeeks.org',
_id: ObjectId("621c3a41fa2fe3c07f43edca") } ],
__v: 7 }
You can use $filter to get documents of given tag as shown below:
Notebook.findOne({
user: "620c81434d8a65c1aa36e0d4" // user ID
},
{
notes: {
$filter: {
input: "$notes",
as: "note",
cond: {
$in: [
"ern", // Tag to search
"$$note.tags"
]
}
}
}
})
Mongo Playground

Whats the error in JavaScript filter Method

While filtering the objects with the filter method I'm unable to filter more than one value with the same ids. Basically, I want to show the object of the same id on the screen
While filtering the objects with the filter method I'm unable to filter more than one value with the same ids. Basically, I want to show the object of the same id on the screen
const services = [
{
id: 1,
technology: "web",
title: "Web Design",
description: "Web design is the process of planning, conceptualizing, and arranging content online. ",
imageUrl: "./images/webDesign.jpg",
details: "https://www.pagecloud.com/blog/web-design-guide"
},
{
id: 1,
technology: "web",
title: "Web Development",
description: "Web development is the work involved in developing a website for the Internet (World Wide Web)",
imageUrl: "./images/webDevelopment.jpeg",
details: "https://en.wikipedia.org/wiki/Web_development"
},
{
id: 1,
technology: "web",
title: "Graphic Design",
description: "Graphic design is a craft where professionals create visual content to communicate messages. ",
imageUrl: "./images/graphic.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 4,
title: "Content Writing",
description: "Content writing is the process of planning, writing and editing web content, typically for digital marketing purposes.",
imageUrl: "./images/contentwriting.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 5,
title: "Seo",
description: "SEO means Search Engine Optimization and is the process used to optimize a website's technical configuration.",
imageUrl: "./images/seo.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 6,
title: "Digital Marketing",
description: "Digital marketing, also called online marketing, is the promotion of brands to connect with potential customers using the internet and other forms of digital communication",
imageUrl: "./images/digital.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 7,
title: "Android Development",
description: "An android developer uses analytical skills and computer training to develop systems for android devices.",
imageUrl: "./images/android.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 8,
title: "eCommerce",
description: "Ecommerce is the buying and selling of goods and services over the Internet. It is conducted over computers, tablets, smartphones, and other smart devices.",
imageUrl: "./images/eco.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
}
]
// Map Method
const cardsContainer = document.querySelector('.cardsContainer');
function apiData(services) {
let cards = services.map((ser)=>{
return `
<div class= "cards">
<img src=${ser.imageUrl} alt="Image Available Soon" />
<h3>${ser.title}</h3>
<p>${ser.description}</p>
Read More
</div> `
})
cardsContainer.innerHTML = cards;
}
apiData(services);
// allShow Btn
function allShow(services){
let cards = services.map((ser)=>{
return `
<div class= "cards">
<img src=${ser.imageUrl} alt="Image Available Soon" />
<h3>${ser.title}</h3>
<p>${ser.description}</p>
All Show
</div> `
});
cardsContainer.innerHTML = cards;
}
// Filter Method webBtn
function webShow(services) {
services.filter((servi)=>{
if(servi.id === 1){
const cards = `
<div class= "cards">
<img src=${servi.imageUrl} alt="Image Available Soon" />
<h3>${servi.title}</h3>
<p>${servi.description}</p>
Web
</div> `
cardsContainer.innerHTML += cards;
}
});
}
// filter method Marketing
function marketing(services) {
services.filter((service)=>{
if(service.id === 6){
let cards = `
<div class= "cards">
<img src=${service.imageUrl} alt="Image Available Soon" />
<h3>${service.title}</h3>
<p>${service.description}</p>
Read More
</div> `
cardsContainer.innerHTML = cards;
}
});
}
// find Method contentBtn
function contentShow(services){
services.find((servic)=>{
if(servic.title === "Content Writing"){
let cards = `
<div class= "cards">
<img src=${servic.imageUrl} alt="Image Available Soon" />
<h3>${servic.title}</h3>
<p>${servic.description}</p>
Read More
</div> `
cardsContainer.innerHTML = cards;
}
});
}
You need to do the filter before processing
It is NOT recommended to update DOM in a loop
Here we generate all the cards in an array and update once
Also wrap attributes in quotes
const cardsContainer = document.querySelector('.cardsContainer');
function show(services,btn) {
return services
.map(servi => `<div class="cards">
<img src="${servi.imageUrl}" alt="Image Available Soon" />
<h3>${servi.title}</h3>
<p>${servi.description}</p>
${btn}
</div> `).join("");
}
function marketing() {
cardsContainer.innerHTML = show(services.filter(({id}) => id === 6),"Marketing")
}
function webShow() {
cardsContainer.innerHTML = show(services.filter(({id}) => id === 1),"Web")
}
function contentShow() {
cardsContainer.innerHTML = show(services.filter(({title}) => title === "Content Writing"),"Content")
}
function allShow() {
cardsContainer.innerHTML = show(services,"All");
}
// show one
webShow()
<div class="cardsContainer"></div>
<script>
const services = [{
id: 1,
technology: "web",
title: "Web Design",
description: "Web design is the process of planning, conceptualizing, and arranging content online. ",
imageUrl: "./images/webDesign.jpg",
details: "https://www.pagecloud.com/blog/web-design-guide"
},
{
id: 1,
technology: "web",
title: "Web Development",
description: "Web development is the work involved in developing a website for the Internet (World Wide Web)",
imageUrl: "./images/webDevelopment.jpeg",
details: "https://en.wikipedia.org/wiki/Web_development"
},
{
id: 1,
technology: "web",
title: "Graphic Design",
description: "Graphic design is a craft where professionals create visual content to communicate messages. ",
imageUrl: "./images/graphic.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 4,
title: "Content Writing",
description: "Content writing is the process of planning, writing and editing web content, typically for digital marketing purposes.",
imageUrl: "./images/contentwriting.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 5,
title: "Seo",
description: "SEO means Search Engine Optimization and is the process used to optimize a website's technical configuration.",
imageUrl: "./images/seo.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 6,
title: "Digital Marketing",
description: "Digital marketing, also called online marketing, is the promotion of brands to connect with potential customers using the internet and other forms of digital communication",
imageUrl: "./images/digital.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 7,
title: "Android Development",
description: "An android developer uses analytical skills and computer training to develop systems for android devices.",
imageUrl: "./images/android.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
},
{
id: 8,
title: "eCommerce",
description: "Ecommerce is the buying and selling of goods and services over the Internet. It is conducted over computers, tablets, smartphones, and other smart devices.",
imageUrl: "./images/eco.jpg",
details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience."
}
]
</script>
Donot perform a loop action using Array.filter. If you want to perfrorm a loop action use Array.forEach or some other loop instead.
If you are looking to filter down your array with elements having id === 1, you can achieve this using.
services.filter((servi) => servi.id === 1)
If you want to update your dome with this filtered result, you can loop through this filtered array and generate the html string and set it as the innerHTML of the target.
Also its recommented(not mandatory) to include src and href attributes inside quotes ""
Updating a dom inside a loop is not a good practice. Frequent update of DOM will impacts the performace of the application. Produce the html string using the loop itration and set this final string as the innerHTML
Working Code
const services = [
{ id: 1, technology: "web", title: "Web Design", description: "Web design is the process of planning, conceptualizing, and arranging content online. ", imageUrl: "./images/webDesign.jpg", details: "https://www.pagecloud.com/blog/web-design-guide" },
{ id: 1, technology: "web", title: "Web Development", description: "Web development is the work involved in developing a website for the Internet (World Wide Web)", imageUrl: "./images/webDevelopment.jpeg", details: "https://en.wikipedia.org/wiki/Web_development" },
{ id: 1, technology: "web", title: "Graphic Design", description: "Graphic design is a craft where professionals create visual content to communicate messages. ", imageUrl: "./images/graphic.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 4, title: "Content Writing", description: "Content writing is the process of planning, writing and editing web content, typically for digital marketing purposes.", imageUrl: "./images/contentwriting.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 5, title: "Seo", description: "SEO means Search Engine Optimization and is the process used to optimize a website's technical configuration.", imageUrl: "./images/seo.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 6, title: "Digital Marketing", description: "Digital marketing, also called online marketing, is the promotion of brands to connect with potential customers using the internet and other forms of digital communication", imageUrl: "./images/digital.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 7, title: "Android Development", description: "An android developer uses analytical skills and computer training to develop systems for android devices.", imageUrl: "./images/android.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 8, title: "eCommerce", description: "Ecommerce is the buying and selling of goods and services over the Internet. It is conducted over computers, tablets, smartphones, and other smart devices.", imageUrl: "./images/eco.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." }
]
// Map Method
const cardsContainer = document.querySelector('.cardsContainer');
function webShow(services) {
const filteredServices = services.filter((servi) => servi.id === 1);
let htmlTemplate = '';
filteredServices.forEach((node) => {
const cards = `
<div class= "cards">
<img src="${node.imageUrl}" alt="Image Available Soon" />
<h3>${node.title}</h3>
<p>${node.description}</p>
Web
</div> `;
htmlTemplate += cards;
});
cardsContainer.innerHTML = htmlTemplate;
}
webShow(services);
<div class="cardsContainer"></div>
A Generic Method
Seperate your template creation logic into a single function and pass the list for each category to this template generation function.
Working Code
const cardsContainer = document.querySelector('.cardsContainer');
const services = [
{ id: 1, technology: "web", title: "Web Design", description: "Web design is the process of planning, conceptualizing, and arranging content online. ", imageUrl: "./images/webDesign.jpg", details: "https://www.pagecloud.com/blog/web-design-guide" },
{ id: 1, technology: "web", title: "Web Development", description: "Web development is the work involved in developing a website for the Internet (World Wide Web)", imageUrl: "./images/webDevelopment.jpeg", details: "https://en.wikipedia.org/wiki/Web_development" },
{ id: 1, technology: "web", title: "Graphic Design", description: "Graphic design is a craft where professionals create visual content to communicate messages. ", imageUrl: "./images/graphic.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 4, title: "Content Writing", description: "Content writing is the process of planning, writing and editing web content, typically for digital marketing purposes.", imageUrl: "./images/contentwriting.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 5, title: "Seo", description: "SEO means Search Engine Optimization and is the process used to optimize a website's technical configuration.", imageUrl: "./images/seo.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 6, title: "Digital Marketing", description: "Digital marketing, also called online marketing, is the promotion of brands to connect with potential customers using the internet and other forms of digital communication", imageUrl: "./images/digital.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 7, title: "Android Development", description: "An android developer uses analytical skills and computer training to develop systems for android devices.", imageUrl: "./images/android.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." },
{ id: 8, title: "eCommerce", description: "Ecommerce is the buying and selling of goods and services over the Internet. It is conducted over computers, tablets, smartphones, and other smart devices.", imageUrl: "./images/eco.jpg", details: "https://www.interaction-design.org/literature/topics/graphic-design#:~:text=Graphic%20design%20is%20a%20craft,to%20optimize%20the%20user%20experience." }
]
function generateTemplate(list) {
let htmlTemplate = '';
list.forEach((node) => {
const cards = `
<div class= "cards">
<img src="${node.imageUrl}" alt="Image Available Soon" />
<h3>${node.title}</h3>
<p>${node.description}</p>
Web
</div> `;
htmlTemplate += cards;
});
cardsContainer.innerHTML = htmlTemplate;
}
// allShow Btn
function allShow() {
// Passing the complete list
generateTemplate(services)
}
// Filter Method webBtn
function webShow() {
// For web only the elements with id 1 needs to be rendered
const list = services.filter(item => item.id === 1);
generateTemplate(list)
}
// filter method Marketing
function marketing() {
// For marketing only the elements with id 6 needs to be rendered
const list = services.filter(item => item.id === 6);
generateTemplate(list)
}
// find Method contentBtn
function contentShow() {
// For content only the elements with title "Content Writing" needs to be rendered
const list = services.filter(item => item.title === "Content Writing");
generateTemplate(list)
}
<button onclick="allShow()">allShow</button>
<button onclick="webShow()">webShow</button>
<button onclick="marketing()">marketing</button>
<button onclick="contentShow()">contentShow</button>
<div class="cardsContainer"></div>

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);
};

Using Arrays in JS

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 :(

Categories