JavaScript - Child elements get duplicated while using a for loop - javascript

The Problem:
I am willing to get a child element called optionName (you may have a look at the JSON array below to have a clearer idea on what's happening), which requires from me a nested for loop in order to get it. So far, I can get; however, the issue appears when I try to assign the value of that child element to a variable (line 5 in the code section), while I am doing the following additions += i.optionName which makes the value of i.optionName to be ordered (one after the other, similar to an array), the child elements get accumulated which makes the following appear:
Meal : Big Mac
Options :
Normal Ou Maxi ? : Maxi
Choix du boisson : Fanta Orange
Choix des frites : Frites steak house
Category : Menus
Qty : 1
Price : 49
Meal : Chicken McNuggets X6
Options :
//The first block is repeated again which is normal as I used additions +=**
Normal OR Big ? : Big
Choix du boisson : Fanta Orange
Choix des frites : Steak house
Normal OR Big ? : Normal
Choix du boisson : Sprite
Choix des frites : Steak house**
Category : Menus
Qty : 1
Price : 45
In short it's getting worse as much as the parent elements are more than that. You may say why I am doing that, the answer is because the below variable dishes it needs to be a string in this special case!
The current code:
let dishes = '';
let additions = '';
var msg = MessageContent.orderedDishes.forEach(function(element) {
for(var i of element.selectedAdditions){
additions += i.optionName +
' : '
+ i.Name + '\n';
}
dishes +=
'Meal : ' + element.dishName + '\n' +
'Options : \n' + additions + '\n' +
'Category : ' + element.categoryName + '\n' +
'Qty : ' + element.qty+ '\n' +
'Price : ' + element.price + '\n\n';
});
Here is the JSON array I am trying to iterate through:
[{
"objectId": "Kakao0MiRE",
"price": 49,
"dishName": "Big Mac",
"categoryName": "Menus",
"selectedAdditions": [{
"optionName": "Normal Ou Big ?",
"Name": "Big",
"Price": 5
}, {
"optionName": "Drink",
"Name": "Fanta Orange",
"Price": 0
}, {
"optionName": "Fries",
"Name": "Steak house",
"Price": 0
}],
"additionalPrice": 5,
"qty": 1
}, {
"objectId": "kOP90Ld8b9",
"price": 45,
"dishName": "Chicken McNuggets X6",
"categoryName": "Menus",
"selectedAdditions": [{
"optionName": "Normal Ou Maxi ?",
"Name": "Normal",
"Price": 0
}, {
"optionName": "Drink",
"Name": "Sprite",
"Price": 0
}, {
"optionName": "Fries",
"Name": "Frites steak house",
"Price": 0
}],
"additionalPrice": 0,
"qty": 1 }]

Your additions variable is defined declared outside of the call to forEach.
When forEach iterates, you concatenate values to the existing value of additions but never reset it to an empty string for each iteration. This is why your data builds up.
You can resolve this by setting the value of additions to an empty string at the beginning of your forEach callback, or by declaring it inside the forEach so that it starts with an empty array for each iteration. I'd suggest the latter:
let dishes = '';
var msg = MessageContent.orderedDishes.forEach(function(element) {
// declaring your variable here ensures that
// it is empty at the beginning of the iteration
// rather than accumulating over all of them:
let additions = '';
for(var i of element.selectedAdditions){
additions += i.optionName + ' : ' + i.Name + '\n';
}
dishes += 'Meal : ' + element.dishName + '\n'
+ 'Options : \n' + additions + '\n'
+ 'Category : ' + element.categoryName + '\n'
+ 'Qty : ' + element.qty+ '\n'
+ 'Price : ' + element.price + '\n\n';
});

Related

Have a Object key value equal the value of another object

So what I the basics is that I am trying to put in mutiple values into a for loop .
I can do one at a time but I am trying to do multiple values.
my html
<form class="form1 "action="">
<input type="text" id="fname" name="fname" value="v" >
</form>
my javascript
let answers2 = document.getElementById('fname').value;
console.log(answers2.split(''));
let answersString = answers2.split('');
console.log(typeof answersString);
var answersObject = _.invert(answersString);
for (let i = 0; i < answers5.length; i++) {
if (M2060[answersObject]) {
let soultion1 = "M" + ((20 + 20).toString() + "," + (60 + 00).toString() + " " + M2060[answers2]);
for example here is the object of M2060
var M2060 = {
"B" : [
" v-40 a20,10 0 0 1 0,20 a20,10 0 0 1 0,20 ",
],
"H" : [
" v-40 v20 h20 v20 v-40 ",
// need to move down
],
"I" : [
" h20 h-10 v-40 h10 h-20 ",
// need to move down
],
"N" : [
" v-36 l20,40 v-40 ",
],
}
and M3060
var M3060 = {
"T" : [
" v-40 h10 h-20 ",
],
"t" : [
" v-20 v10 h10 h-20 "
],
}
So lets say I put in Bt in my html which are in two differnt objects
answers2 collects the value you put in the html
answersString changes it into an object array
where it would be
0: "B"
1: "t"
but answersObject changes it to
"B": 0
"t": 1
how can I have them both go into my if statement and collect the value connected to the key that they are both assigned to in a different object ?
tldr : how can I have MUTIPLE values detect that their values are the same as the key of another object and changes the key to the key of the object .
That the original key = the value.
EDIT:
So I guess the simplest way I can say this is lets
Say in a object 0: ["g"] and 1 :["H"]
and in another object g: "wow" and "H" :[Help]
how can I get "g" from 0 to change to "wow" which in a different object
so 0 would = 0: ["wow"]
but at the same time 1 would change to 1: ["Help"].

Choosing an array/object to search from using variable name, with Javascript and jQuery

I'm a total beginner with JavaScript. I have code that randomly picks an item from an object and now I'd like to randomly pick an item from an object that shares the name as whatever was picked in the first round of generation. I'm not sure how to use a variable name in a selector, especially if that variable name is itself, uh, variable!
Right now I'm getting "undefined" for pizzaFirstChoice.option. I'd like to be getting either "extra sausage", "extra pepperoni", etc, as .option if "meatlover" is picked from "pizzaStyles" and either "extra mushroom", "extra onion", etc, if "veggielover" is picked from "pizzaStyles". The code is successfully generating and displaying .size and .style.
I feel like I'm doing an awful job at describing this, but hopefully you can see what I'm after by looking at the code.
function generate() {
var pizzaFirstChoice = {
size: "",
style: "",
option: "",
};
var pizzaSizes = [
"small",
"medium",
"large",
];
var pizzaStyles = [
"meatlover",
"veggielover",
];
var meatlover = [
"extra sausage",
"extra pepperoni",
"extra bacon",
];
var veggielover = [
"extra mushroom",
"extra onion",
"extra bell pepper",
];
pizzaFirstChoice.size = pizzaSizes[Math.floor(Math.random()*pizzaSizes.length)];
pizzaFirstChoice.style = pizzaStyles[Math.floor(Math.random()*pizzaStyles.length)];
pizzaFirstChoice.option = pizzaFirstChoice.style[Math.floor(Math.random()*pizzaFirstChoice.style)];
var pizza = $("#result").html("His first choice of pizza is a " + pizzaFirstChoice.size + " " + pizzaFirstChoice.style + " with " + pizzaFirstChoice.option + ".");
}
You can define meatlover and veggielover as properties of an object; use bracket notation to reference
pizzaFirstChoice.style as property of object with [Math.floor(Math.random() * pizzaOptions[pizzaFirstChoice.style].length)] to adjacent right to reference .length of the selected array.
function generate() {
var pizzaFirstChoice = {
size: "",
style: "",
option: "",
};
var pizzaSizes = [
"small",
"medium",
"large",
];
var pizzaStyles = [
"meatlover",
"veggielover",
];
// define `meatlover`, `veggielover` arrays as properties of an object
var pizzaOptions = {
meatlover: [
"extra sausage",
"extra pepperoni",
"extra bacon",
]
, veggielover: [
"extra mushroom",
"extra onion",
"extra bell pepper",
]
};
pizzaFirstChoice.size = pizzaSizes[Math.floor(Math.random() * pizzaSizes.length)];
pizzaFirstChoice.style = pizzaStyles[Math.floor(Math.random() * pizzaStyles.length)];
pizzaFirstChoice.option = pizzaOptions[pizzaFirstChoice.style][Math.floor(Math.random() * pizzaOptions[pizzaFirstChoice.style].length)];
var pizza = $("#result").html("His first choice of pizza is a " + pizzaFirstChoice.size + " " + pizzaFirstChoice.style + " with " + pizzaFirstChoice.option + ".");
}
generate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
if you input console.log after each pizzaFirstChoice.. you will see tha first and second wil give you an answer: medium veggielover, and the third one will be undefined.
However you are multiplying string pizzaFirstChoice.style with Math.random() - of course it is undefined.
the question is what do you want to be pizzaFirstChoice.option - in the same way you can query array length for meatlover and for veggie lover:
pizzaFirstChoice.option = meatlover[Math.floor(Math.random()*meatlover.length)];
or
pizzaFirstChoice.option = veggielover[Math.floor(Math.random()*veggielover.length)];
I think that i get correctly what you are after. if not - please explain what is the desired output
Try a conditional:
function generate() {
var pizzaFirstChoice = {
size: "",
style: "",
option: "",
};
var pizzaSizes = [
"small",
"medium",
"large",
];
var pizzaStyles = [
"meatlover",
"veggielover",
];
var meatlover = [
"extra sausage",
"extra pepperoni",
"extra bacon",
];
var veggielover = [
"extra mushroom",
"extra onion",
"extra bell pepper",
];
pizzaFirstChoice.size = pizzaSizes[Math.floor(Math.random()*pizzaSizes.length)];
pizzaFirstChoice.style = pizzaStyles[Math.floor(Math.random()*pizzaStyles.length)];
if (pizzaFirstChoice.style == 'meatlover') {
pizzaFirstChoice.option = meatlover[Math.floor(Math.random()*meatlover.length)];
} else if (pizzaFirstChoice.style == 'veggielover') {
pizzaFirstChoice.option = veggielover[Math.floor(Math.random()*veggielover.length)];
}
$("#result").html("His first choice of pizza is a " + pizzaFirstChoice.size + " " + pizzaFirstChoice.style + " with " + pizzaFirstChoice.option + ".");
}

Map object into array then output value with jQuery

I have the below javascript which puts a list of customers into an object, then outputs then on the page.
var name = ["andrew", "vic", "casey"];
var job = ["builder", "baker", "dentist"];
var product = [111, 222, 111];
var qty = [1, 2, 3];
var data = {};
for (i = 0; i < name.length; i++) {
a = {
"name": name[i],
"job": job[i],
"product": product[i],
"qty": qty[i]
};
a['xtra-' + product[i]] = qty[i];
data[name[i]] = a;
console.log(a);
}
data = $.map(data, function (val, key) {
return val;
});
data.sort();
$.each(data, function (i, val) {
$('body').append(val.name + ' - ' + val.job + ' - ' + val.product + ' - ' + val.qty + ' - ' + (val.xtra + val.product) + '<br>');
});
With what I have so far see fiddle, I am outputting the persons name - job - product - qty.
andrew - builder - 111 - 1 - NaN<br>
vic - baker - 222 - 2 - NaN<br>
casey - dentist - 111 - 3 - NaN<br>
I am also trying to print out some extra information which is storred in my object called 'xtra-' + product[i].
This is being storred in a as you can see from the console log eg xtra-222 however, I can't get it outputting in my each statement?
I understand what I have done
val.xtra + val.product
is trying to add a number with a string and this is why it isn't working but I can't seem to get work out what syntax is required (possibly getting the last nth item) here or maybe there is another method to acheive what I want here?
In case there is any confusion I want my output to be
andrew - builder - 111 - 1 - 1
vic - baker - 222 - 2 - 2
casey - dentist - 111 - 3 - 3
Where the last 1,2,3 comes from the value 'xtra-' + product[i] stored in a
The problem is inside the .each loop, more specifically in (val.xtra + val.product).
The val object for the first run of that loop is:
Object {name: "andrew", job: "builder", product: 111, qty: 1, xtra-111: 1}
As you can see, there's no xtra key in that object, instead you have an xtra-111 key. So if you use (val['xtra-' + val.product] + val.product) you'll get the result that you need.
Here's the fixed code http://jsfiddle.net/VdVax/
in your $.each did you mean
val["xtra-" + val.product]
?
Here is a working fiddle http://jsfiddle.net/p5Zhc/3/

Cannot read undefined property error - building object properties in JavaScript

I am taking an online JavaScript class and am stuck on a problem involving objects. In the following code, my assignment is to output a string that retrieves the name of each ranger (e.g. lighthouseRock.ranger1.name) and match their station to the corresponding item in the superBlinders array.
If I hard-code the ranger1 property, the output format is in the right ballpark. However, if I try to be creative and build a variable (thisRanger) to dynamically insert the appropriate ranger into my object, the routine returns an error "TypeError: Cannot read property 'name' of undefined". My thisRanger variable builds OK but whenever I try to insert it into my chain after lightHouseRock it causes the undefined problem. Here is my code:
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock.thisRanger.name + ", man the " + superBlinders[lighthouseRock.thisRanger.station][0];
};
console.log(message);
}
The expected output should look something like this:
Avast, me hearties!
There be Pirates nearby! Stations!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
How can I insert thisRanger into my code so that it gives me the expected output? Thank you very much for your help!
Working code!
It outputs all you want it todo!
UPDATE you have an error in your code I fixed that also..
Ranger2 will always be stationed on undefined since there aren't 3 stations when counting as an array, remember array in javascript starts counting from 0(zero). I changed Drew barontini to "0"
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
CODE OUTPUT
Avast, me hearties!
There be Pirates nearby! Stations!
Nick Walsh, man the Supernova,12000 Drew Barontini, man the Firestorm,4000Christine Wong, man the Solar Death Ray,6000
I didn't do much to change your code. But what I did is that I change your code into
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
Its important to know with javascript that you can use brackets [] to get to an object property if you build the stirng dynamicly.
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
};
console.log(message);
}
dontPanic();

How to create random data but with meaningful relation?

var lc_relationship={"sensor1":[
{
"ObjectID":"sens1_001",
"Parent":null,
"child": sens2_050
"z cordinate": -5
},
{
"ObjectID":"sens1_002",
"Parent":null,
"child": sens2_072
"z cordinate": -5
}
.
.
.
uptill ObjectID : sens1_100
],
"sensor2":[
{
"ObjectID":"sens2_001",
"Parent":sens1_068,
"child": sens3_010
"z cordinate": 0
},
{
"ObjectID":"sens2_002",
"Parent":sens1_040,
"child": sens3_080
"z cordinate": 0
}
.
.
.
uptill ObjectID : sens2_100
],
"sensor3":[
{
"ObjectID":"sens3_001",
"Parent":sens2_055,
"child": null
"z cordinate": 5
},
{
"ObjectID":"sens3_002",
"Parent":sens2_029,
"child": null
"z cordinate": 5
}
.
.
.
uptill ObjectID : sens3_100
]
}
I need to store the relationship of geometry in some data structure so that later should be helpful to track either wise to access the derived geometry. I made a detail picture, so that one could get the better idea. Could someone help..?
If I understood your question, you have very concrete data (100 cones placed in 3 layers), and what you want to randomize is the relationship between them.
If so, then next code may give you what you need: It randomly picks a cone from first layer, then sets a relation to a randomly selected cone from the second layer, for which also sets a relation to a randomly selected cone from the third layer (no cone is selected twice in any layer, as in your description). Here is a jsFiddle with a working implementation: http://jsfiddle.net/roimergarcia/j2uLE.
NOTES:
The 10x10 grid that is on the drawing may be easily generated form the indexes of the sensor arrays.
If you are going to generate more than 100 cones per layer (100000?) or a lot of layers, you may need to optimize this algorithm.
//A helping function
function rightPad(number) {
var tmpStr = number.toString();
return ("000" + tmpStr).substring(tmpStr.length, tmpStr.length+3);
}
//The generator function
function generateData(){
var nSize = 100,
lc_relationship,
aSensor1 = [],
aSensor2 = [],
aSensor3 = [],
lc_relationship = {
"sensor1":[],
"sensor2":[],
"sensor3":[]
}
for(i=1; i<=nSize; i++){
aSensor1.push(i);
aSensor2.push(i);
aSensor3.push(i);
}
for(n=0; n<nSize; n++){
var pos1 = Math.floor(Math.random() * (nSize-n));
var pos2 = Math.floor(Math.random() * (nSize-n));
var pos3 = Math.floor(Math.random() * (nSize-n));
var int1 = aSensor1[pos1]; aSensor1.splice(pos1,1);
var int2 = aSensor2[pos2]; aSensor2.splice(pos2,1);
var int3 = aSensor3[pos3]; aSensor3.splice(pos3,1);
lc_relationship.sensor1[int1-1] = {
"ObjectID" : "sens1_" + rightPad(int1),
"Parent":null,
"child": "sens2_" + rightPad(int2),
"z cordinate": -5
}
lc_relationship.sensor2[int2-1] = {
"ObjectID" : "sens2_" + rightPad(int2),
"Parent":"sens1_" + rightPad(int1),
"child": "sens3_" + rightPad(int3),
"z cordinate": 0
}
lc_relationship.sensor3[int3-1] = {
"ObjectID" : "sens3_" + rightPad(int3),
"Parent":"sens2_" + rightPad(int2),
"child": null,
"z cordinate": 5
}
}
return lc_relationship;
}
console.log(generateData());

Categories

Resources