JS - How to populate an array with objects from another greater object - javascript

I am traying to populate an array "array1" with objects with format {a:'value', b:'value'} that come from a greater objet "objPractice", (could be a json). I don't know what I am doing wrong but I get an array with objects all equals corresponding just with the last element of the original object. I need all of them, not just the last one.
This is the code:
let objPractice = {
books: [
{
isbn: "9781449325862",
title: "Git Pocket Guide",
subtitle: "A Working Introduction",
author: "Richard E. Silverman",
publish_date: "2020-06-04T08:48:39.000Z",
publisher: "O'Reilly Media",
pages: 234,
description: "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git exp",
website: "http://chimera.labs.oreilly.com/books/1230000000561/index.html"
},
{
isbn: "9781449331818",
title: "Learning JavaScript Design Patterns",
subtitle: "A JavaScript and jQuery Developer's Guide",
author: "Addy Osmani",
publish_date: "2020-06-04T09:11:40.000Z",
publisher: "O'Reilly Media",
pages: 254,
description: "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-da",
website: "http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/"
},
{
isbn: "9781449337711",
title: "Designing Evolvable Web APIs with ASP.NET",
subtitle: "Harnessing the Power of the Web",
author: "Glenn Block et al.",
publish_date: "2020-06-04T09:12:43.000Z",
publisher: "O'Reilly Media",
pages: 238,
description: "Design and build Web APIs for a broad range of clients—including browsers and mobile devices—that can adapt to change over time. This practical, hands-on guide takes you through the theory and tools you need to build evolvable HTTP services with Microsoft",
website: "http://chimera.labs.oreilly.com/books/1234000001708/index.html"
},
{
isbn: "9781449365035",
title: "Speaking JavaScript",
subtitle: "An In-Depth Guide for Programmers",
author: "Axel Rauschmayer",
publish_date: "2014-02-01T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 460,
description: "Like it or not, JavaScript is everywhere these days-from browser to server to mobile-and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who o",
website: "http://speakingjs.com/"
},
{
isbn: "9781491904244",
title: "You Don't Know JS",
subtitle: "ES6 & Beyond",
author: "Kyle Simpson",
publish_date: "2015-12-27T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 278,
description: "No matter how much experience you have with JavaScript, odds are you don’t fully understand the language. As part of the \\\"You Don’t Know JS\\\" series, this compact guide focuses on new features available in ECMAScript 6 (ES6), the latest version of the st",
website: "https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20&%20beyond"
},
{
isbn: "9781491950296",
title: "Programming JavaScript Applications",
subtitle: "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
author: "Eric Elliott",
publish_date: "2014-07-01T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 254,
description: "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flex",
website: "http://chimera.labs.oreilly.com/books/1234000000262/index.html"
},
{
isbn: "9781593275846",
title: "Eloquent JavaScript, Second Edition",
subtitle: "A Modern Introduction to Programming",
author: "Marijn Haverbeke",
publish_date: "2014-12-14T00:00:00.000Z",
publisher: "No Starch Press",
pages: 472,
description: "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale ",
website: "http://eloquentjavascript.net/"
},
{
isbn: "9781593277574",
title: "Understanding ECMAScript 6",
subtitle: "The Definitive Guide for JavaScript Developers",
author: "Nicholas C. Zakas",
publish_date: "2016-09-03T00:00:00.000Z",
publisher: "No Starch Press",
pages: 352,
description: "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that E",
website: "https://leanpub.com/understandinges6/read"
}
]}
And here is the code to populate the new array "array1"
let obj1 = { isbn: "", title: "" }
let array1 = []
for (var i=0; i < objPractica.books.length - 1; i++) {
obj1.isbn = objPractica.books[i].isbn
obj1.title = objPractica.books[i].title
array1.push(obj1)
}
console.log("The array [] that contains object with format {a:'value', b:'value'} is: ", array1)
But these is the result that I am getting:
The array [] that contains object with format {a:'value', b:'value'} is: [
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
}
]
As you can see, I just get only the last element from the original object. Why is that?

This is a fun learning experience about object references (see this article for some short reading). Follow my comments in this code snippet:
// You are creating an object here:
let obj1 = { isbn: "", title: "" }
let array1 = []
for (var i=0; i < objPractice.books.length - 1; i++) {
// You are changing properties on the _existing_ object "obj1" here:
obj1.isbn = objPractice.books[i].isbn
obj1.title = objPractice.books[i].title
// You are pushing another copy of "obj1" into the array.
array1.push(obj1)
}
You are not creating a new object in each iteration of your for loop. You are just changing the properties on the existing object (obj1) and adding another copy of it to your array.
How about this:
for (var i=0; i < objPractice.books.length - 1; i++) {
array1.push({
isbn: objPractice.books[i].isbn,
title: objPractice.books[i].title
})
}
or even better still, use some of the helpful Array prototype methods like map to make this even simpler:
const array1 = objPractice.books.map(book => ({
isbn: book.isbn,
title: book.title
}))

Related

ReactJS export excel with xlxs-populate nested array of object how

I'm looking for a way to export excel file for nested array of object using xlxs-populate library, language is reactjs. I don't see this get mention in the official document, i make sure to check thoroughly (or perhap i'm missing please be kindly leave a comment), or perhap this feature hasn't been implemented yet? I'm looking forward for your insight. For an easier depiction, here's how the data should look like:
[
{
title: "title1",
content: [
{
imageUrl: "http://placehold.it/300x300",
title: "Campaigns",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "Events",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "General",
description:
"Short description explaining the use of this design in a single sentence."
}
]
},
{
title: "title2",
content: [
{
imageUrl: "http://placehold.it/300x300",
title: "Video Template A",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "Video Template A",
description:
"Short description explaining the use of this design in a single sentence."
}
]
}
];

Is there a way to format a JavaScript object logged to console in vscodes integrated git bash terminal?

I'm currently working with a an object and loading it into the terminal console with console.log(books)
The code for the object is this.
const books = [
{
id:1,
name: "Harry Potter and the Chamber of Secrets",
authorId: 1
},
{
id: 2,
name: "Harry Potter and the Prisoner of Azkaban",
authorId: 1
},
{
id: 3,
name: "Harry Potter and the Goblet of Fire",
authorId: 1
},
{
id: 4,
name: "The Fellowship of the Ring",
authorId: 2
},
{
id: 5,
name: "The Two Towers",
authorId: 2
},
{
id: 6,
name: "The Return of the King",
authorId: 2
},
{
id: 7,
name: "The Way of Shadows",
authorId: 3
},
{
id: 8,
name: "Beyond the Shadows",
authorId: 3
},
];
It's quite a small problem, but I've noticed that not all of the information is displayed consistently when I log to console. Is this a problem with the git bash terminal or the integration between vscode and git bash and is there anything that can be done to make the presentation more consistent? It's a bit jarring.
I've tried looking for resources on this issue and haven't found anything similar. Would be great to get ideas as even if it's a small thing, when looking through larger data sets, it would be nice to know it will be formatted consistently.
I found a great answer to this on Handy Tips on Using Console Log
You can use Stringify to structure big objects and create consistent formatting.
If I type the following it formats nicely.
console.log(JSON.stringify(books, null, 2))

How do I add an if and else statement so it gives me related movies when the current movie is loaded?

Here's my code.
I have a movies related tab and when a specific movie is open in a browser, under the related tab, related movies should be there. I have the map functions ready which load all the movies I have in the map object. Wanted an if and else statement to pick the same genre of movies by using a getElementId to get the id genre of the current movie and compare it with the genre in the map objects. Hope am using the right terms
//create test div
const data = [{
name: "13 reasons why",
href: "13 reasons why.php",
img: "https://images.theconversation.com/files/170594/original/file-20170523-5763-161mnda.jpg",
describe: "Newcomer Katherine Langford plays the role of Hannah, a young woman who takes her own life. Two weeks after her tragic death, a classmate named Clay finds a mysterious box on his porch. Inside the box are recordings made by Hannah -- on whom Clay had a crush -- in which she explains the 13 reasons why she chose to commit suicide. If Clay decides to listen to the recordings, he will find out if and how he made the list. This intricate and heart-wrenching tale is told through Clay and Hannah's dual narratives.",
rate: "7.6",
date: "(2017 - 2020)"
}, {
name: "30 Coins",
href: "30 coins.php",
img: "https://www.themoviedb.org/t/p/w500/b2i9aaV6ncULl9jYXEoPi7VFJg8.jpg",
describe: "Father Vergara, an exorcist, boxer and ex-convict exiled to a remote town in Spain, enlists the help of the mayor and a veterinarian when a series of paranormal phenomena begins to occur.",
rate: "7.2",
date: "(2020 - Present)"
}, {
name: "911 Lone Star",
href: "911 lone star.php",
img: "https://m.media-amazon.com/images/I/717AkBpHNjL._AC_SY450_.jpg",
describe: "9-1-1: Lone Star follows a sophisticated New York firefighter who, along with his son, relocates from Manhattan to Austin, Texas. He must try to balance the duties of saving those who are at their most vulnerable and solving the problems in his own life. ",
rate: "6.8",
date: "(2017 - 2021)"
}, {
name: "911",
href: "911.php",
img: "https://m.media-amazon.com/images/M/MV5BMzNiMmNmZWQtMTJlMS00NWIyLTlhNmEtNmI3M2Q1YjczMGI4XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_.jpg",
describe: "Policemen, paramedics and firefighters put themselves in dangerous situations to save people's lives. Meanwhile, they also have to deal with their personal problems.",
rate: "7.6",
date: "(2018 - Present)"
}, {
name: "A confession",
href: "a confession.php",
img: "https://m.media-amazon.com/images/M/MV5BZTc0ZjQxOWEtNTc4MS00ZjgxLThkOWEtZGM1NzgzOWYwOTc1XkEyXkFqcGdeQXVyMTAyNjU1NjU5._V1_.jpg",
describe: "The true story of DS Stephen Fulcher and his hunt for missing 22-year-old Sian O'Callaghan, and how it lead to the arrest of Christopher Halliwell. This was the beginning of the capture of a prolific serial killer and the detectives own downfall.",
rate: "7.6",
date: "(2019)"
}, {
name: "A million little things",
href: "a million little things.php",
img: "http://www.gstatic.com/tv/thumb/tvbanners/17114373/p17114373_b_v12_aa.jpg",
describe: "The lives of a group of carefree friends from Boston change when one of them shockingly dies. They soon realise the importance of cherishing their friendship.",
rate: "7.9",
date: "(2018)"
}, {
name: "A teacher",
href: "a teacher.php",
img: "https://m.media-amazon.com/images/M/MV5BZjgzMmUwZjgtNzNhMi00M2Y0LWIxOTAtYzYzODdjMTYzZWQyXkEyXkFqcGdeQXVyMTIwNDUyNzMy._V1_.jpg",
describe: "This drama series examines the complexities and consequences of an illicit sexual affair between a young teacher and her student. Claire is a new teacher at Westerbrook High School in Texas. Dissatisfied in her marriage to her college sweetheart, Claire's life changes when Eric, a personable teenager in her English class, takes an interest in her. Popular and outgoing, Eric is the captain of the soccer team and nearly inseparable from his best friends. Everything seems perfect on the surface, but Eric is forced to juggle the pressures of school, applying for college and a part-time job, all while helping take care of his two younger brothers. Claire and Eric discover an undeniable connection that allows them to escape their lives, but their relationship accelerates faster than either could anticipate. The permanent damage left in the wake of their illicit affair becomes impossible for them, and their friends and family, to ignore.",
rate: "6.9",
date: "(2020)"
}, {
name: "Absentia",
href: "absentia.php",
img: "https://m.media-amazon.com/images/M/MV5BNmFiNDI5ODUtODQ2ZC00ZjUwLWFhYjQtMjk3MmMzZjY1ZWU2XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: ">Six years after going missing and being declared dead, FBI agent Emily Byrne is found alive in a cabin in the woods. With no memory of her past, she sets out to reclaim her life and identity.",
rate: "7.3",
date: "(2017 - 2020)"
}, {
name: "After Life",
href: "after life.php",
img: "https://m.media-amazon.com/images/M/MV5BZjdjOWIxMDgtYTgwNS00MjE4LTliZWYtZGI1NDhhZmIyYjM1XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "Tony had a perfect life -- until his wife Lisa died. After that tragic event, the formerly nice guy changed. After contemplating taking his life, Tony decides he would rather live long enough to punish the world by saying and doing whatever he likes. He thinks of it as a superpower -- not caring about himself or anybody else -- but it ends up being trickier than he envisioned when his friends and family try to save the nice guy that they used to know. Golden Globe winner Ricky Gervais stars in the comedy series, which he also writes and directs.",
rate: "8.4",
date: "(2019 - 2020)"
}, {
name: "Alex Rider",
href: "alex rider.php",
img: "https://m.media-amazon.com/images/M/MV5BOTg4ZmQ5ZjItZTllZC00NzUzLTkwMTEtMjIzYzliZjk2ODUwXkEyXkFqcGdeQXVyMTEyMjM2NDc2._V1_.jpg",
describe: "London teenager Alex Rider is recruited by the Department of Special Operations, a subdivision of the Secret Intelligence Service (MI6), to infiltrate a controversial corrective academy for the wayward offspring of the ultra-rich.",
rate: "7.6",
date: "(2020)"
}, {
name: "All Rise",
href: "all rise.php",
img: "https://m.media-amazon.com/images/M/MV5BYTk5ZjI0M2MtYjQ5Ny00OWJmLWExYWEtNjRlMTdkNjYwMGIzXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "A look inside the chaotic, hopeful and sometimes absurd lives of judges, prosecutors and public defenders as they work with bailiffs, clerks and cops to get justice for the people of Los Angeles amidst a flawed legal process. Among them is newly appointed Judge Lola Carmichael, a highly regarded and impressive deputy district attorney who doesn't intend to sit back on the bench in her new role, but instead leans in, immediately pushing the boundaries and challenging the expectations of what a judge can be.",
rate: "6.7",
date: "(2019 - 2021)"
}, {
name: "Altered Carbon",
href: "altered carbon.php",
img: "https://m.media-amazon.com/images/M/MV5BNjIxMWMzMzctYmZkYy00OTkzLWFlMWUtMjc3ZDFmYzQ3YmVkXkEyXkFqcGdeQXVyNjU2ODM5MjU#._V1_.jpg",
describe: "More than 300 years in the future, society has been transformed by new technology, leading to human bodies being interchangeable and death no longer being permanent. Takeshi Kovacs is the only surviving soldier of a group of elite interstellar warriors who were defeated in an uprising against the new world order. His mind was imprisoned for centuries until impossibly wealthy businessman Laurens Bancroft offers him the chance to live again. Kovacs will have to do something for Bancroft, though, if he wants to be resurrected. Bancroft's request of Kovacs is to solve a murder Bancroft's. 'Altered Carbon' is based on Richard K. Morgan's cyberpunk noir novel of the same name.",
rate: "8",
date: "(2018 - 2020)"
}, {
name: "American Horror Story",
href: "american horror story.php",
img: "https://flxt.tmsimg.com/assets/p9423798_b_v12_ad.jpg",
describe: "An anthology series centering on different characters and locations, including a house with a murderous past, an insane asylum, a witch coven, a freak show circus, a haunted hotel, a possessed farmhouse, a cult, the apocalypse, a slasher summer camp, and a bleak beach town and desert valley.",
rate: "7.6",
date: "(2011 - Present)"
}, {
name: "Anne With An E",
href: "anne with an e.php",
img: "https://m.media-amazon.com/images/M/MV5BNThmMzJlNzgtYmY5ZC00MDllLThmZTMtNTRiMjQwNmY0NmRhXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_FMjpg_UX1000_.jpg",
describe: "This reimagining of the classic book and film is a coming-of-age story about a young orphan who is seeking love, acceptance and her place in the world. Amybeth McNulty stars as Anne, a 13-year-old who has endured an abusive childhood in orphanages and the homes of strangers. In the late 1890s, Anne is mistakenly sent to live with aging siblings, Marilla and Matthew Cuthbert, who live on Prince Edward Island. Anne, who proves to be uniquely spirited, imaginative and smart, transforms the lives of Marilla, Matthew and everyone else in their small town.",
rate: "8.7",
date: "(2017 - 2019)"
}, {
name: "animal kingdom",
href: "animal kingdom.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BOTk1NjAwOTM1OV5BMl5BanBnXkFtZTgwMzUwODQ3NzM#._V1_FMjpg_UX1000_.jpg",
describe: "After the death of his mother, Joshua decides to live with his grandmother, who heads a criminal clan. His life takes a turn as he gets involved with his cousins and their criminal activities.",
rate: "8.2",
date: "(2016 - Present)"
}, {
name: "Arrow",
href: "arrow.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BMTI0NTMwMDgtYTMzZC00YmJhLTg4NzMtMTc1NjI4MWY4NmQ4XkEyXkFqcGdeQXVyNTY3MTYzOTA#._V1_.jpg",
describe: "After mastering the skill of archery on a deserted island, multi-millionaire playboy Oliver Queen returns to his city to take on the vigilante persona of Arrow to fight crime and corruption.",
rate: "7.5",
date: "(2012 - 2020)"
}, {
name: "Atypical",
href: "atypical.php",
img: "https://m.media-amazon.com/images/M/MV5BMjNjNThmYTUtMjY2Ni00OGE4LTgzOTItYTgzMDllNDM5NTI5XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_FMjpg_UX1000_.jpg",
describe: "This heartfelt comedy follows Sam, a teenager on the autism spectrum, who has decided he is ready for romance. In order to start dating -- and hopefully find love -- Sam will need to be more independent, which also sends his mother (Jennifer Jason Leigh) on her own life-changing path. She and the rest of Sam's family, including a scrappy sister and a father seeking a better understanding of his son, must adjust to change and explore what it means to be normal. The series is created and written by Robia Rashid and Academy Award-winning producer Seth Gordon.",
rate: "8.3",
date: "(2017 - 2021)"
}]
const createTest = (selector) => {
const test = document.querySelector(selector)
console.log(selector)
let html = ''
data.map(({
id,
name,
href,
img,
describe,
rate,
date
}, index) => {
html = `
${html}
<div class="movie-item-style-2">
<div id="product${index}" class="mv-item-infor">
<img src="${img}" alt="">
<h6 style="padding-top: 1em;">${name} <span>${date}</span></h6>
<p class="rate"><i class="ion-android-star"></i><span>${rate}</span> /10</p>
<p class="describe">${describe}</p>
</div>
</div>
`
})
test.innerHTML = html
}
createTest(".content")
<div id="moviesrelated" class="tab">
<div class="row">
<h3>Related Movies</h3>
<div class="test"></div>
<div class="topbar-filter">
<p>Found <span>12 movies</span> in total</p>
<label>Sort by:</label>
<select>
<option value="popularity">Popularity Descending</option>
<option value="popularity">Popularity Ascending</option>
<option value="rating">Rating Descending</option>
<option value="rating">Rating Ascending</option>
<option value="date">Release date Descending</option>
<option value="date">Release date Ascending</option>
</select>
</div>
<div class="content">
</div>
<div class="topbar-filter">
<label>Movies per page:</label>
<select>
<option value="range">5 Movies</option>
<option value="saab">10 Movies</option>
</select>
<div class="pagination2">
<span>Page 1 of 2:</span>
<a class="active" href="#">1</a>
2
<i class="ion-arrow-right-b"></i>
</div>
</div>
</div>
</div>

Combine JSON Arrays in Javascript with

I am trying to learn/use Node and Javascript by re-coding a PHP/MYSQL application I made that is not very efficient - as I built it while I was trying to earn those technologies as well.
I am trying to re-use a some of the information that is created or stored in JSON format.
I have in one file a set of 52 questions that looks like such...
//questions.json
{
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
},
"Administration" : {
"Question 9": "Administration positively supports faculty in a professional manner.",
"Question 10": "Administration actively encourages a dialogue concerning school related issues.",
"Question 11": "Administration is actively engaged in developing/supporting/maintaining a clear school vision.",
"Question 12": "Administration makes sure that the financial stability and integrity of the school is well maintained.",
"Question 13": "Administration/Ownership uses school funds to support the well being of the school."
},...
I also have a Knex script that does a query on the data and returns an array like below....
[ { Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5,
Q9: 7.63,
Q10: 8.13,
Q11: 8.5,
Q12: 8.88,
Q13: 8.75,
Q14: 7.38,
Q15: 8.13,
Q16: 8.56,...
I would like to try to combine these two arrays to look like...
{
"School" : {
{"Question 1" : {
"Question" : "The facilities of the school adequately provide for a positive learning/working experience.",
"Average" : 8.44
},
{"Question 2" : {
"Question" : ""School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc."",
"Average" : 9.13
}
If need be I can remove the category divisions within the .json file if that make combining easier, but in the end applications I display the data in sections, so I will eventually filter it. I just thought maybe dividing it in the json file would make it easier.
I am able to concat the arrays, and I have looked at .map but I am not sure how I would apply it to this. It looks like I would need a nested loop?
Using a double forEach loop:
const questions = {
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
}
};
const scores = {
Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5
};
// Placeholder for your result
const result = {};
// Iterate through the question categories:
const categories = Object.keys(questions);
categories.forEach(cat => {
// Add category to result
result[cat] = {};
// Get the question keys for that category
const questionKeys = Object.keys(questions[cat]);
questionKeys.forEach(q => {
// Get the score key. i.e: Question 1 -> Q1
const scoreKey = q.replace('Question ', 'Q');
// Add question to result
result[cat][q] = {
Question: questions[cat][q],
Average: scores[scoreKey]
};
});
});
console.log(result);
What I do below is basically:
I take the question number out of "Question 1"
Combine it with "Q" to get "Q1"
And then the plain old key lookup in the object you have based on this new string.
All this, in loops below
var newObj = {};
// replace /*questions.json*/ with your actual object.
for (var category in /*questions.json*/){
var questionsObj = /*questions.json*/[category];
newObj[category] = {}
for (var question in questionsObj) {
newObj[category][question] = {};
newObj[category][question].question = questionsObj[question];
var qNumber = question.split("Question ")[1];
newObj[category][question].Average = dataArray[0]["Q"+qNumber];
}
}

Looping through object and inputing into certain indexes using jQuery

I am looking to loop through an object and input into certain indexes using jQuery. I am using Sweet Alert 2 and the chaining modals but I need to generate the titles dynamically. The titles are in the array below.
The object used by SA2 is the following:
var steps = [{
title: 'Questions',
input: 'radio',
inputOptions: inputOptions,
}]
I guess 'each' of some kind after the squared bracket.
["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
Essentailly I need to create:
var steps = [{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
},
{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
}]
Thank you for any help
You can use Array.map()
es6
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(e => ({title:e,input:"radio",inputOptions:{}}));
console.log(result)
es5
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(function(e){
return {title:e,input:"radio",inputOptions:{}};
});
console.log(result)
You need a template object:
var step = {
title : '',
input : 'radio',
inputOptions : inputOptions
};
Then you will just iterate through the array:
var titles = [
"Washing Machine diagnosis",
"Washing Machine type",
...
"Do you have a receipt?"
];
var steps = titles.map((title) => {
var clone = Object.assign({}, step);
clone.title = title;
return clone;
});
or just use Underscore.js to clone objects if you do not like assign()
How about this
$.each(steps, function(i, step){
step.title = myArray[i];
});
This uses JQuery to loop through the array.
I'm not sure i've understand your question but how about this
const titles = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
const steps = titles.map((title) => {
return {
title,
input: 'radio',
inputOptions
}
})

Categories

Resources