Extract Values from nested Json list - javascript

How can I get javascript to read the values "at the end" of the json list below.
i am currently using the code below, except that this code does not read the last 3 values, with different formatting, of the list below i.e.
Extract of Json list:
{...... 'Design_Lump_Sum': {0: {'** Preliminary Design': '2366. 0'},
1: {'** Detailed Design': '15379.0'}, 2: {'** Const Stage Services':
'4732.0'}} }
Code:
var obj = JSON.parse(data);
var keys = Object.keys(obj.Design_Lump_Sum);
for (var asset in keys) {
console.log(asset + " -> " + keys[asset] + " = " + obj.Design_Lump_Sum[keys[asset]]);
}
var keys1 = Object.keys(obj.Capex_Lump_Sum);
for (var asset in keys1) {
console.log(asset + " -> " + keys1[asset] + " = " + obj.Design_Lump_Sum[keys1[asset]]);
}
var keys2 = Object.keys(obj.Opex_Lump_Sum);
for (var asset in keys2) {
console.log(asset + " -> " + keys2[asset] + " = " + obj.Design_Lump_Sum[keys2[asset]]);
}
var keys3 = Object.keys(obj.Provisional_Sum);
for (var asset in keys3) {
console.log(asset + " -> " + keys3[asset] + " = " + obj.Design_Lump_Sum[keys3[asset]]);
}
var keys4 = Object.keys(obj.Management_fees);
for (var asset in keys4) {
console.log(asset + " -> " + keys4[asset] + " = " + obj.Design_Lump_Sum[keys4[asset]]);
}
var keys5 = Object.keys(obj.CSA);
for (var asset in keys5) {
console.log(asset + " -> " + keys5[asset] + " = " + obj.Design_Lump_Sum[keys5[asset]]);
}
Full JSON list:
{
"Management_fees":{ },
"Capex_Lump_Sum":{
"Refrigerant piping":"48040.447",
"Preparation of Mops":"2137.681",
"Labels":"653.016",
"Penetrations and Protection":"1535.534",
"AC Plinth and Trays":"5221.762",
"Insulated Panel Windows":"6527.794",
" MSSB":"19582.199",
"Make Good Walls and Floors":"4154.696",
"Controls":"24092.978",
"** Building Surveyor Fee (Misc)":"7038.85",
"Project Management, Supervision":"38447.5",
"Painting":"9138.675",
"Preliminaries":"1306.032",
"Package system wiring":"16971.318",
"Warranty":"2610.881",
"Ductwork, Valves and Dampers":"77262.913",
"Unit type":"89107.109",
"Structural Engineer for new unit stands":"3916.913",
"Manuals":"3823.456",
"AMS and BMS works":"3916.913",
"Accoustic Report":"4243.421",
"Lighting":"5033.665",
"Drawings":"3823.456",
"Temp Cooling":"10443.524",
"Commissioning":"3263.897",
"Crane":"3003.637",
"Demolition":"26455.429",
"Fire detection and Alarm FIP modifications":"3263.897",
"LSL":"1939.81059657",
"Economy Cycle":"23169.055"
},
"Provisional_Sum":{
"Condenser Roof Platform":"20000.0",
"Removal of ladder outside cable chamber exit stairs":"10000.0"
},
"Opex_Lump_Sum":{ },
"CSA":{
"Additional Hendry Fees":"3742.5",
"External Ladder":"10147.0",
"Asbestos removal Works Total ($42,485.15) (remainder of cost $30K under PS sum)":"12485.15"
},
"Design_Lump_Sum":{
"0":{
"** Preliminary Design":"2366.0"
},
"1":{
"** Detailed Design":"15379.0"
},
"2":{
"** Const Stage Services":"4732.0"
}
},
"Total":{
"sub_Total":"number:530154.0105965699"
}
}

If I don't misunderstood your question then you can try like this.
var obj={'Management_fees':{},'Capex_Lump_Sum':{'Refrigerant piping':'48040.447','Preparation of Mops':'2137.681','Labels':'653.016','Penetrations and Protection':'1535.534','AC Plinth and Trays':'5221.762','Insulated Panel Windows':'6527.794',' MSSB':'19582.199','Make Good Walls and Floors':'4154.696','Controls':'24092.978','** Building Surveyor Fee (Misc)':'7038.85','Project Manag ement, Supervision':'38447.5','Painting':'9138.675','Preliminaries':'1306.032','Package system wiring':'16971.318','Warranty':'2610.881','Ductwork, Valves and Dampers':'77262.913','Unit ty pe':'89107.109','Structural Engineer for new unit stands':'3916.913','Manuals':'3823.456','AMS and BMS works':'3916.913','Accoustic Report':'4243.421','Lighting':'5033.665','Drawings':'38 23.456','Temp Cooling':'10443.524','Commissioning':'3263.897','Crane':'3003.637','Demolition':'26455.429','Fire detection and Alarm FIP modifications':'3263.897','LSL':'1939.81059657','Ec onomy Cycle':'23169.055'},'Provisional_Sum':{'Condenser Roof Platform':'20000.0','Removal of ladder outside cable chamber exit stairs':'10000.0'},'Opex_Lump_Sum':{},'CSA':{'Additional Hendry Fees':'3742.5','External Ladder':'10147.0','Asbestos removal Works Total ($42,485.15) (remainder of cost $30K under PS sum)':'12485.15'},'Design_Lump_Sum':{0:{'** Preliminary Design':'2366. 0'},1:{'** Detailed Design':'15379.0'},2:{'** Const Stage Services':'4732.0'}},'Total':{'sub_Total':'number:530154.0105965699'}};
var data = obj.Design_Lump_Sum;
Object.keys(data).map(function(item,index){
Object.keys(data[item]).map(function(key) {
console.log(key, "->", data[item][key]);
});
});

Related

Basic JavaScript - How to randomly compare two properties from an array of objects

I have an exercise where from an object constructor, I have created several objects, all with an ID property.
The first part of the exercise consist in pairing each object, compare their markAv properties and print the one that had it bigger.
[ a vs b => b wins]
They suggested to do so by using the ID property but I didn't know how to do it that way... so I tried a workaround, as you will see in the code below.
However, the second part of the exercise wants me to do the same but, this time, creating the pairs randomly. Here I have tried to use the ID property by generating a random number that matches the ID but I don´t know how to structure the code for it to work.
The output for the second part should be the same as above, with the only difference that the pairing is now randomly generated.
I have added a partial solution for the second part, partial because from time to time it throws an error that I can´t identify. However, I think I'm getting close to get my desired output.
I would really appreciate if anyone could give me a hint for me to crack the code below and to get it working because I really want to understand how to do this.
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function getPairs(array) {
function getPairs(array) {
for (let i = 0; i < array.length; i += 2) {
if (array[i].markAv < array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i + 1].name + " Wins")
} else if (array[i].markAv > array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i].name + " Wins")
}
}
}
getPairs(heroes)
///
function randomAv(array) {
let result = []
let hero1 = heroes[Math.floor(Math.random() * 6) + 1]
for(let i = 0; i<array.length; i++){
if (array[i].markAv <= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + array[i].name + " Wins"))
} else if(array[i].markAv >= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + hero1.name + " Wins"))
}
}
console.log(result)
}
First shuffle the array:
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
let heroes_shuffle = heroes.sort((a, b) => 0.5 - Math.random())
Then do as normal
getPairs(heroes_shuffle )
All Possible Combination :
function allPairs(heroes) {
while (heroes) {
[hero, ...heroes] = heroes
for (enemy of heroes) {
if (hero.markAv === enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": draw")
else if (hero.markAv < enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": " + enemy.name + " Wins")
else
console.log(hero.name + " vs " + enemy.name + ": " + hero.name + " Wins")
}
}
}
You can take the function from here https://stackoverflow.com/a/7228322/1117736
And do something like this:
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
let hero1 = heroes[randomIntFromInterval(1, 6)]
let hero2 = heroes[randomIntFromInterval(1, 6)]
if (hero1.markAv < hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero1.name + " Wins")
} else if(hero1.markAv > hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero2.name + " Wins")
}

madlibs generator webpage with javascript

I want to use only 1 input bar to cycle through different prompts asking the user to input nouns, verbs, adjectives, etc. I want it to cycle through every time the user presses the 'enter' key. And at the very end, I want the entire madlib paragraph to print out at the bottom with the stored user input values. I think using an array was correct in order to store the user input values.. I'm stuck. Am I doing this right??
full codepen with HTML and CSS here (to see my simple concept idea): https://codepen.io/stanimal93/pen/GRJGeEb
let prompt = document.getElementById('prompt');
let input = document.getElementById('userinput');
let madlib = document.getElementById('madlibparagraph');
input.addEventListener("keyup", submit(event));
input.addEventListener("keyup", resetInput);
input.addEventListener("keyup", changePrompt);
function submit(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
}
function resetInput() {
input.value = "" // to clear the input
}
function changePrompt() {
let word = new Array();
word[0] = "a location: "
word[1] = "a living thing: "
word[2] = "a name: "
word[3] = "a kind of food: "
word[4] = "a noun: "
word[5] = "a verb: "
word[6] = "a color: "
word[7] = "a plural noun: "
word[8] = "a sound: "
for (i = 0; i < 10; i++) {
prompt.innerHTML = word[i];
word[i] = input.value
};
}
// var location = "a location: "
// var livingThing = "a living thing: "
// var name = "a name: "
// var food = "a kind of food: "
// var noun = "a noun: "
// var verb = "a verb: "
// var color = "a color: "
// var pluralNoun = "a plural noun: "
// var sound = "a sound: "
// let words = [location, livingThing, name, food, noun, verb, color, pluralNoun, sound]
let madib.innerHTML = "Once upon a time in " + _______ + ", there was a " + _______ + " named " + _________ + ". The world was stricken by coronavirus in the year 2020 and there was no " + ________ + " to eat anymore. " + ________ + " went outside to find " + _________ + " and realized everyone was " + ________ + ". There were " + ________ + " colored " + __________ + " and you could hear " + ___________ + " in the distance.";
Solved and finished it myself and it is bug free! I had trouble wrapping my head around using a for loop as opposed to an if statement during an eventListener keypress event, along with a fadein type of function. Feel free to play it! in this codepen: https://codepen.io/stanimal93/pen/GRJGeEb
$(document).ready(function() {
let prompt = document.getElementById('prompt');
let input = document.getElementById('userinput');
let madlib = document.getElementById('madlibparagraph');
function resetInput() {
input.value = '' // to clear the input
}
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
prompt.style.opacity = 0;
storeAnswer();
resetInput();
setTimeout(fadein, 500);
function fadein() {
prompt.style.opacity = 1;
changePrompt();
}
}
});
let word = new Array();
word[0] = "a living thing: "
word[1] = "a name: "
word[2] = "a kind of food: "
word[3] = "a noun: "
word[4] = "a verb: "
word[5] = "a color: "
word[6] = "a plural noun: "
word[7] = "a sound: "
word[8] = "Read your madlib below!"
var i = 0
function changePrompt() {
if (i < 9) {
console.log(i);
prompt.innerHTML = word[i];
console.log(answer);
i++
}
if (i === 9) {
madlib.innerHTML = "Once upon a time in " + answer[0].toUpperCase().bold() + ", there was a " + answer[1].toUpperCase().bold() + " named " + answer[2].toUpperCase().bold() + ". The world was stricken by coronavirus in the year 2020 and there was no " + answer[3].toUpperCase().bold() + " to eat anymore. " + answer[2].toUpperCase().bold() + " went outside to find " + answer[4].toUpperCase().bold() + " and realized everyone was " + answer[5].toUpperCase().bold() + ". There were " + answer[6].toUpperCase() + " colored " + answer[7].toUpperCase().bold() + " and you could hear " + answer[8].toUpperCase().bold() + " in the distance.";
}
}
function storeAnswer() {
for (var a = 0; a < 9; a++) {
answer[i] = input.value;
}
}
let answer = new Array();
answer[0] = ""
answer[1] = ""
answer[2] = ""
answer[3] = ""
answer[4] = ""
answer[5] = ""
answer[6] = ""
answer[7] = ""
answer[8] = ""
});

Checking for a value in an Array inside of a JSON file

I have a JSON file for which I have created a jQuery function to find matching values and and display them in a div. I'm not quite sure how to compare a single value within the activitiesarray in the JSON file. It only seems to return the entire array.
How do I check through each resortin the JSON file and see if one of the values in the activities array inside the JSON file contains a specific value like scuba diving
JavaScript:
var destination = $('option:selected', "#destination").attr('value');
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value');
var date = $('option:selected', "#date").attr('value');
var price = $('option:selected', "#price").attr('value');
$.getJSON('resort.json', function(data) {
$.each(data.resorts, function(key, val) {
if (destination == val.destination) {
if (comfortLevel == val.comfortLevel || activties == val.activities || date == val.startDate || price > val.price) {
$("#resortData").html("<img src= "+val.picture+" class='miniPic'> Destination: "+ val.destination + "<br>" + "Name: " + val.name + "<br>" +"Location: "
+ val.location + "<br>" + "Comfort: " + val.comfortLevel + " Star <br>" + "Activities: " + val.activities + "<br>" + "Price: £"
+ val.price + "<br>" + "Start Date: " + val.startDate + "<br>" + "End Date: " + val.endDate + "<br>" + "Description: " + val.short_description
+ "<br><br>" + "<a href=':" + val.url +"'>Click HERE for more info</a>");
}
}
});
});
resort.JSON:
{
"resorts": [
{
"id":"resort1",
"destination":"Carribean",
"name":"Les Boucaniers",
"location":"Martinique",
"comfortLevel": "4",
"activities":["water skiing", "tennis", "scuba diving", "kitesurf", "spa"],
"price":1254,
"startDate":"2016-01-01",
"endDate":"2016-12-31",
"short_description":"The resort of Les Boucaniers is located on the laid-back beach-covered south coast of the island, and is perfectly placed for Martinique holidays that are both relaxing and awe-inspiring.",
"picture":"images/resort1pic1small.jpg",
"long_description":"A divers' paradise in the Baie du Marin, a legendary spot.<br>Its bungalows are discreetly lodged in a tropical garden beside the white sand beach in superb Marin Bay. A magical site where you can enjoy a taste of everything, alone or with family or friends. Try water sports and the magnificent Club Med Spa*. You'll be enchanted by the exotic flavours of the local cuisine and the joyful spirit of the Caribbean.",
"url":"resorts/resort1.html"
},
{
"id":"resort2",
"destination":"Indian Ocean",
"name":"La Plantation d'Albion",
"location":"Mauritius",
"comfortLevel": "5",
"activities":["kids club","golf", "scuba diving", "flying trapeze", "tennis", "sailing", "spa"],
"price":2062,
"startDate":"2016-01-01",
"endDate":"2016-12-31",
"short_description":"Beautifully located in one of the last remote creeks on the island, La Plantation d'Albion Club Med welcomes the most demanding of guests into a world of supreme refinement.",
"picture":"images/resort2pic1small.jpg",
"long_description":"In a remote beauty spot, savour the luxury of Mauritian lifestyle. <br> The idyllic natural setting is enhanced by the sublime decor designed by Marc Hertrich and Nicolas Adnet, and the Resort's top-end comfort is perfectly reflected in its beautifully spacious rooms. The exceptional CINQ MONDES Spa* and luxurious overflow pool add an ideally Zen touch.<br> The Resort is entirely devoted to fulfilling its guests' desires and offers discreet, personal service in its swimming areas, bars and 'Table Gourmet' restaurants.",
"url":"resorts/resort2.html"
}
]}
How do I check through each resortin the JSON file and see if one of
the values in the activities array inside the JSON file contains a
specific value like scuba diving
Use indexOf() on the activities array.
NB there's a typo (activties ) here: if (comfortLevel == val.comfortLevel || activties == val.activities ...
A little tricky, but sometimes a RegExp helps in this type of situations and saves a lot of code:
var escape = /[.?*+^$[\]\\(){}|-]/g;
var destination = $('option:selected', "#destination").attr('value').replace(escape, "//$&");
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value').replace(escape, "//$&");
var date = $('option:selected', "#date").attr('value').replace(escape, "//$&");
var price = $('option:selected', "#price").attr('value');
$.get('resort.json', function(data) {
var json = JSON.parse( data.match(new RegExp('(\{[^\{\}]*?"destination"\s*\:\s*"' + destination + '"[^\}]*(?:"comfortLevel"\s*\:\s*"' + comfortLevel + '"|"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]|"date"\s*\:\s*"' + date + '"|"price"\s*\:\s*(?:' + "[0-" + price.split("").join("]?[0-") + "]?" + '))[^\{\}]*?\})'))[0] );
$("#resortData").html("<img src= "+json.picture+" class='miniPic'> Destination: "+ json.destination + "<br>" + "Name: " + json.name + "<br>" +"Location: "
+ json.location + "<br>" + "Comfort: " + json.comfortLevel + " Star <br>" + "Activities: " + json.activities + "<br>" + "Price: £"
+ json.price + "<br>" + "Start Date: " + json.startDate + "<br>" + "End Date: " + json.endDate + "<br>" + "Description: " + json.short_description
+ "<br><br>" + "<a href=':" + json.url +"'>Click HERE for more info</a>");
});
The specific piece of RegExp to test if an activities is contained in the Array is this:
'"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]'

Using JS .split and join with an array multiple times. It only runs the last pair

I'm trying to use JS to parse a text input field on keyup, to show the same text with all the pronouns changed. It should read: I, me, mine and produce:
you, you, yours
s/he, s/he, hers/his
they, them, theirs
It works perfectly for the first set of replacements. On the second and third sets it only replaces the last variable set in the array. :(
I'm sure there is a more efficient way to write this code. I've made each section completely duplicative trying to solve my problem to no available. I fear I'm making a simple mistake.
Here's a fiddle if you'd like to take a pass at it.
http://jsfiddle.net/8k9b83mo/3/
Here's the raw JS:
function grammar() {
text = ' ' + document.getElementById("first_p").value + ' ';
var array = {
" my ": " your ",
" myself ": " yourself ",
" mine ": " yours ",
" I ": " you ",
" me ": " you ",
" our ": " your "
};
for (var val in array)
text = text.split(val).join(array[val]);
document.getElementById('2_pe').innerHTML = text;
text2 = ' ' + document.getElementById("first_p").value + ' ';
var array2 = {
" my ": " her/his ",
" myself ": " herself/himself ",
" mine ": " hers/his ",
" I ": " s/he ",
" me ": " s/he ",
" our ": " her/his "
};
for (var val2 in array2)
text_3pe1 = text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text_3pe1;
text3 = ' ' + document.getElementById("first_p").value + ' ';
var array3 = {
" my ": " their ",
" myself ": " themself ",
" mine ": " theirs ",
" I ": " they ",
" me ": " they ",
" our ": " their "
};
for (var val3 in array3)
text_3pe2 = text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text_3pe2;
}
Thanks so much for your help! I'm pulling my hair out on this one.
You aren't updating text2 and text3 each time through the for loop, so only the last changes are saved to text_3pe1 and text_3pe2. Replace text_3pe1 with text2 and text_3pe2 with text3, like this, and you should get the result you're looking for.
you are using the wrong variables in your forEach methods
change the following lines :
text_3pe1 = text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text_3pe1;
text_3pe2 = text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text_3pe2;
for
text2= text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text2;
text3= text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text3;
it was doing the substitutions, just in the wrong place.
here is the fiddle http://jsfiddle.net/ucpfL2bs/
As others have said you are not updating the correct variables in your for loops. However I think you should reconsider your approach a bit. Right now you're splitting and joining on every iteration of the loop which is a bit unnecessary.
This approach allows you to reduce your similar code and replaces the words in a temporary array and joins back once:
function grammar() {
replace(document.getElementById('first_p').value, {
"my": "your",
"myself": "yourself",
"mine": "yours",
"I": "you",
"me": "you",
"our": "your"
}, document.getElementById('2_pe'));
replace(document.getElementById('first_p').value, {
"my": "her/his",
"myself": "herself/himself",
"mine": "hers/his",
"I": "s/he",
"me": "s/he",
"our": "her/his"
}, document.getElementById('3_pe1'));
replace(document.getElementById('first_p').value, {
"my": "their",
"myself": "themself",
"mine": "theirs",
"I": "they",
"me": "they",
"our": "their"
}, document.getElementById('3_pe2'));
}
function replace(inputText, replacements, displayElement) {
var words = inputText.split(' ');
for (var i = 0; i < words.length; i++) {
var word = words[i];
if (replacements[word.trim()]) {
words[i] = replacements[word].trim();
}
}
displayElement.innerHTML = words.join(' ');
}
Updated JSFiddler

So I've restarted my While-loop program and now am getting all NaN or they aren't saving the text I input

I need to write a program for a wedding planner. They wish to create a gift registry for each couple. They want the gifts broken down by the whether the gift giver is on the bride side or groom side. They also know that specific gifts (toasters, silverware, and stemware) tend to be repeated so they want those gifts listed and have the name of the gift giver under them. The repeating gifts are only the ones that have been told you by the client (toasters, silverware, and stemware) they do not want you to determine which gifts repeat, they are just looking for those specific three. So I can implement code for only silverware, stemware, and toasters, which I have this time. But now I cannot get any correct output.
After the program has run, it should have a printout somewhat like this.
Groom side:
Tom: toaster
Bill: silverware
Bob: stemware
Steve: Lexus
Bride side:
Jill: toaster
Suzy: silverware
Pat: stemware
Karen: horse
Multiple toasters by:
Tom
Jill
Multiple silverware by:
Bill
Suzy
Multiple stemware by:
Bob
Pat
Here is what I've got so far...
var guestName;
var gift, side, kind, groomNameAccum, brideNameAccum;
var toaster, silverware, stemware, giftType;
var toasterAccum, silverwareAccum, stemwareAccum;
var noGift = 0;
var groomCounter = 0;
var brideCounter = 0;
//initalizing loop
var guest = "yes";
//start loop
while (guest == "yes") {
side = prompt("Which side are you on? groom or bride?", "");
guestName = prompt("Whats your name?", "");
kind = prompt("What kind of gift?", "");
if (side == "groom") {
groomCounter = groomCounter + 1;
if (groomCounter == 1) {
groomNameAccum = "Groom side: <br>" + groomCounter + ". " + guestName + ": " + kind;
} else {
groomNameAccum = groomNameAccum + "<br>" + groomCounter + ". " + guestName + ": " + kind;
}
} else
if (side == "bride") {
brideCounter = brideCounter + 1;
if (brideCounter == 1) {
brideNameAccum = "<p>Bride side: <br>" + brideCounter + ". " + guestName + ": " + kind;
} else {
brideNameAccum = brideNameAccum + "<br>" + brideCounter + ". " + guestName + ": " + kind;
}
}
if (kind == "toaster")
{
toasterAccum = toasterAccum + "; " + guestName;
}
else if(kind == "silverware")
{
silverwareAccum= silverwareAccum + "; " + guestName;
}else if (kind == "stemware")
{
stemwareAccum = stemwareAccum + "; " + guestName
}
else
{
multiples = 0;
}
guest = prompt("Are there anymore guests?", "yes");
}
document.write(groomNameAccum);
document.write(brideNameAccum);
document.write("<p>Multiple Toasters by:<br>" + toasterAccum + "<br/>");
document.write("Multiple Silverware by:<br>" + silverwareAccum + "<br/>");
document.write("Multiple Stemware by:<br>" + stemwareAccum + "<br/>");
As I was saying, my teacher doesn't try to teach us the shortcuts and easy stuff, because it is a classroom of technical college students. I know there are easier ways to write it out, but I don't know how yet. Hes got his formula for success that always leads me looking for correct answers....

Categories

Resources