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
In my Angular app with a MongoDB/Node backend, I have been successfully iterating over an array of records and printing them to the view in a table layout - one line per object in the array.
Now I have a situation where I need to break out what was information on one line into three lines, based on info in a "subdata" object. A simplified version of the data looks like this:
data: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
subdata: {
a: "value a",
b: "value b",
c: "value c"
},
deleted: false
}
]
Rather than iterating once for each object in the "data" array, which I was doing before like this:
<tr *ngFor="let record of records.data | paginate: { id: 'results', itemsPerPage: 12, currentPage: getPageNumber(), totalItems: records.count }">
... I instead need to now print three lines - one for each of the values in the "subdata" object. But each of those lines needs to include the name, the birthDate, and the city that is part of the parent object.
From an architectural point of view, does it make it more sense to create a new backend endpoint, and populate the data in the format I want to iterate over it by (which would involve some repetition of props and values (name, birthDate, city, etc...), like this:
reOrgedData: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
a: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
b: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
c: value
deleted: false
}
]
or is there a way I can iterate over this in its original data structure, but still break it out into three lines in the view?
My sense is that creating a custom endpoint with the data organized in the form I need is the way to go, even though that does involve some repetition. This approach makes for less hoops-jumping on the front-end. But I am curious for people's take on what would be the best approach in a scenario like this.
I have a mustache file, and I am iterating over the array:
var data = {
sales: [
{
name: "Jim Frost",
region: "USA East",
phone: "212-555-1212",
email: "jfrost#acme-travel.com"
},
{
name: "Jan Smith",
region: "USA West",
phone: "310-555-1212",
},
{
name: "Fred Wesley",
phone: "608-555-1212",
email: "fwesley#acme-travel.com"
},
{
name: "Lisa Moore",
region: "USA South",
phone: "315-555-1212",
email: "lmoore#acme-travel.com"
},
{
name: "Jim Dio",
phone: "+ 44 022-555-1212",
email: "jdio#acme-travel.com"
},
{
name: "Charles Watts",
region: "Spain",
email: "cwatts#acme-travel.com"
},
{
name: "Bert Cooper",
region: "Italy",
email: "bcooper#acme-travel.com"
}
]
};
here is the markup:
<div>
<section>
{{#data.sales}}
<article class="items">
<div class="region">{{{region}}}</div>
</article>
{{/data.sales}}
</section>
</div>
I want to add some special style (like, bold font, color etc) ONLY if the region is USA East.
how can i detect inside this inherent loop in the article element if {{{region}} has a specific value? Given that the comparison will be made against a value that i get from backend, say {{myValue}}, which is manually set to USA East in the backend.
You can add a function in the data which will return the correct class depending on the region value. Something like
data['regionClass'] = function(){
if ( this['region'] == 'USA East' ) {
return "strong green";
}else{
return "";
}
}
And then in the Mustache you can do: <div class="region {{regionClass}}">{{{region}}}</div>
I am putting together a simple book sorter app and I am having some trouble using the filterBy filter. The filter works fine for filtering the non-fiction genre but for some reason it does not work for fiction. I want to display the book titles and authors, and then in the input field, filter through the list of books being displayed by genre. So if I write fiction in the input field, it should only display the fiction books. This is what my view looks like:
<div id="app">
<h1>{{title}}</h1>
<div id="input">
<input type="text" v-model="genre" placeholder="Search fiction/non-fiction">
</div>
<div id="display-books" v-for=" book in books | filterBy genre in 'genre' ">
<span>Title: {{book.title}}</span>
<span>Author: {{book.author}}</span>
</div>
</div>
And here is my app.js:
var appData = {
title: 'Book Sorter',
filters: 'Search filter',
filtertext: '* only show title if book is available',
genre: '',
books:
[
{genre: "fiction", title: "The Hobbit", author: "J.R.R Tolkien", available: false},
{genre: "non-fiction", title: "Homage to Catalonia", author: "George Orwell", available: true},
{genre: "non-fiction", title: "The Tipping Point", author: "Malcolm Gladwell", available: false},
{genre: "fiction", title: "Lord of the Flies", author: "William Golding", available: true},
{genre: "fiction", title: "The Call of the Wild", author: "Jack London", available: true}
]
}
new Vue({
el: "#app",
data: appData,
});
There is no problem with your setup, Vue's filterBy is working fine in your example. When you type fiction, it will show all Books because they all have the word fiction in the genre, meaning that: fiction and non-fiction both contains fiction, returning true.
Create a custom filter like this:
Vue.filter('match', function (value, input) {
return input ? value.filter(function(item) {
return item.genre === input ? value : null;
}) : value;
});
And change selection from an input to dropdown:
<select v-model="genre">
<option value="" selected>Select Genre</option>
<option value="fiction">Fiction</option>
<option value="non-fiction">Non-Fiction</option>
</select>
Here is a fiddle implementing it: https://jsfiddle.net/crabbly/br8huz7c/