I'm making an incremental game and I have what I want working in a JSFiddle but I can't for the life of me get it to work on my actual website. Here's what happens on my website.
Here's my code for working this out:
SetInterval(function() {
for(var outer in user.upgrades)
{
for(var inner in user.upgrades[outer])
{
loadedUser.upgrades[outer][inner].cost = Math.floor(user.upgrades[outer][inner].cost * Math.pow(user.upgrades[outer][inner].scale, loadedUser.upgrades[outer][inner].owned));
}
}
}, 10);
The loadedUser object and user object:
var costScaling = 1.15;
const user = {
"name": "",
"stats": {
"click": 1,
"level": 1,
"xp": 0,
"melons": 0,
"mps": 0,
},
"upgrades": {
"melons": {
"mash": {
"name": "Mash - 1MPS",
"cost": 50,
"value": 1,
"owned": 0,
"scale": costScaling
}
The loadedUser would be the same as this however in the upgrades.melons in the amount but there would be how many they own.
So, my issue is as you can see in the gyazo is that it turns into a really big number very quickly however on the JSFiddle is exactly what I want and I'm struggling to get it work locally, on the console is the value of user.upgrades which shouldn't even change. If you need anymore code just ask.
Related
I'm trying to create DOM elements for an Ingredient filter bar, based on JSON file objects.
The problem is that the same ingredient can appear in several objects, and in that case it should only create the dom element once, not for each time the ingredient occures.
I've tried with childNode, value, innerHTML and !=== but can't figure out the solution. It either creates no element at all, or all of them with duplicates.
Any ideas?
Here is a codePen to help : https://codepen.io/enukeron/pen/eYdgyzx
I also tried with an array to keep track of seen values at this codepen :
https://codepen.io/enukeron/pen/ExgZoLa
JS:
const ingredientDropdown = document.getElementById('ingredientDropdown');
for(var j = 0; j < IngredientList.length; j++) {
if (ingredientDropdown.children.textContent !== IngredientList[j].ingredient) {
var ingredientSearchItems = document.createElement("p");
ingredientSearchItems.textContent = IngredientList[j].ingredient;
ingredientDropdown.appendChild(ingredientSearchItems);
}
}
The JSON file has this format :
{
"id": 49,
"name": "Tropical smoothie",
"servings": 4,
"ingredients": [
{
"ingredient": "Bananas",
"quantity": 2
},
{
"ingredient": "Kiwis",
"quantity": 3
},
{
"ingredient": "Mango",
"quantity": 1
},
{
"ingredient": "Pineapple",
"quantity": 4,
"unit":"slices"
},
{
"ingredient": "Honey",
"quantity": 2,
"unit": "tablespoons"
}
],
"time": 0,
"description":"Chop the fruit. Liquefy in the blender. Chill. Serve",
"appliance": "Blender",
"ustensils":["couteau", "verres"]
}, etc.....
The actual result is :
The Expected Result is :
You could create a function like the following:
function filterIngredients(recipes){
let return_arr = [];
recipes.forEach((recipe, index, array)=>{
let ingredients = recipe["ingredients"];
ingredients.forEach((ingredient, index, inner_array)=>{
if(!return_arr.includes(ingredient["ingredient"])){
return_arr.push(ingredient["ingredient"]);
}
});
});
return return_arr;
}
And then call the function as follows:
var ingredients = filterIngredients(recipes);
You can then loop through ingredients and display them in the div as you want (hoping this is what you wanted in the first place).
Here is a link to my pen where I implemented it:
https://codepen.io/AnirudhMS/pen/MWjJQgg?editors=1010
I have a site in which there is a <script> with a JSON inside. With user script in Tampermonkey, I want to get that JSON to work with it later.
So I thought that I can get it with getElemntsByTagName("script"), but I couldn't figure out how to get string out of it.
How do you get a string from getElemntsByTagName("script"), like console.log does?
Is there an easier way to do so?
window.wpProQuizInitList = window.wpProQuizInitList || [];
window.wpProQuizInitList.push({
id: '#wpProQuiz_67',
init: {
quizId: 67,
mode: 2,
globalPoints: 76,
timelimit: 0,
resultsGrade: [0],
bo: 3,
qpp: 0,
catPoints: [76],
formPos: 0,
lbn: "\u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u0438 \u0442\u0435\u0441\u0442",
json: {
"2944": {
"type": "single",
"id": 2944,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
"2945": {
"type": "single",
"id": 2945,
"catId": 0,
"points": 1,
"correct": [0,1,0,0]
},
"2946": {
"type": "single",
"id": 2946,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
…
}
}
}
You can use document.querySelector to get the first <script> element; there is no need to obtain a live HTMLCollection to get one element. You can then read its textContent.
let value = document.querySelector('script').textContent;
getElementsByTagName("script") will return an HTMLCollection which contains a list of script tags. You can get the text of the first script tag like this:
getElementsByTagName("script")[0].innerText
I've been trying to use an online API (albion-online-data.com) for a while in sheets, creating a little function to try to grab a specific identifier, sell_price_min, but the function keeps returning undefined.
I've been looking around for ages but haven't been able to find out what's wrong. Sorry, I'm new to APIs and google sheets in general. I used Logger.log, and it shows the correct contents after Json.parse, but when trying to use
return w.sell_price_min;
it always returns undefined.
Here's the code:
/**
* Retrieve the current price for a given city.
*
*/
function CURRENTPRICE(name, location, quality) {
name = encodeURI(name);
location = encodeURI(location);
quality = encodeURI(quality);
var response = UrlFetchApp.fetch("http://www.albion-online-data.com/api/v2/stats/Prices/" + name + "?locations=" + location + "&qualities=" + quality);
var w = JSON.parse(response.getContentText());
return w.sell_price_min;
}
and the API is:
https://www.albion-online-data.com/api/v2/stats/prices/T4_BAG,T5_BAG?locations=Caerleon,Bridgewatch&qualities=2
which returns the following: (reformatted here with indentation and line breaks for readability)
[
{
"item_id": "T4_BAG",
"city": "Bridgewatch",
"quality": 2,
"sell_price_min": 4000,
"sell_price_min_date": "2019-09-02T22:20:00",
"sell_price_max": 4444,
"sell_price_max_date": "2019-09-02T22:20:00",
"buy_price_min": 0,
"buy_price_min_date": "0001-01-01T00:00:00",
"buy_price_max": 0,
"buy_price_max_date": "0001-01-01T00:00:00"
},
{
"item_id": "T4_BAG",
"city": "Caerleon",
"quality": 2,
"sell_price_min": 5571,
"sell_price_min_date": "2019-09-03T11:05:00",
"sell_price_max": 5571,
"sell_price_max_date": "2019-09-03T11:05:00",
"buy_price_min": 2375,
"buy_price_min_date": "2019-09-03T08:41:00",
"buy_price_max": 4020,
"buy_price_max_date": "2019-09-03T08:41:00"
},
{
"item_id": "T5_BAG",
"city": "Bridgewatch",
"quality": 0,
"sell_price_min": 20000,
"sell_price_min_date": "2019-09-01T14:00:00",
"sell_price_max": 22100,
"sell_price_max_date": "2019-09-01T14:00:00",
"buy_price_min": 0,
"buy_price_min_date": "0001-01-01T00:00:00",
"buy_price_max": 0,
"buy_price_max_date": "0001-01-01T00:00:00"
},
{
"item_id": "T5_BAG",
"city": "Caerleon",
"quality": 2,
"sell_price_min": 23897,
"sell_price_min_date": "2019-09-03T11:03:00",
"sell_price_max": 26376,
"sell_price_max_date": "2019-09-03T11:03:00",
"buy_price_min": 15000,
"buy_price_min_date": "2019-09-02T22:21:00",
"buy_price_max": 22550,
"buy_price_max_date": "2019-09-02T22:21:00"
}
]
and the results should be: 4000?
Sorry for any hassle... I've been stumped for literally hours .-.
You are accessing a JSON array. So it should be
for(var i = 0; i < w.length; i++) {
var obj = w[i];
console.log(obj.sell_price_min);
}
If you want to get the first value of the array put
return w[0].sell_price_min
I would need help making a data structure with mongodb.
I'm using JavaScript to manipulate data.
I would like to have a document structure of this type, but i'm not sure to do the right thing. I noticed that you tend to use the array also as a container of objects, and i also noticed that the mongodb update operators need a structure of this type. for example:
var mydoc = {
_id: ObjectId("5099803df3f4948bd2f98391"),
items:[ {"name": "name", "other": "other"},
{"name": "name", "other": "other"},
{"name": "name", "other": "other"}
]}
but organize data in this way do not like :) how i would like the document:
{
"_id": {
"$oid": "dfdsdsfdsff54sdf5ds"
},
"displayName": "name",
"userId": "h8566d9482gghffhtry565",
"info": {
"level": 1,
"currentExperience": 0,
"requiredExperience": 0,
"missingExperience": 0
},
"statistics": {
"total": {
"stat1": 0,
"stat2": 0,
"stat3": 0,
"stat4": 0
},
"best": {
"distance": 0,
"stat1": 0,
"stat2": 0,
"stat3": 0,
"stat4": 0
},
"game": {
"one": 0,
"two": 0,
"three": 0,
"stat4": 0
}
},
"inventory": {
"item1": {
"property1": 0,
"property2": 0,
"property3": 0,
"property4": 0,
"level": {
"level": 1,
"currentExperience": 0,
"requiredExperience": 0,
"missingExperience": 0
},
"skins": [
"skin1",
"skin2",
"skin3"
]
},
"item2": {
"property1": 0,
"property2": 0,
"property3": 0,
"property4": 0,
"level": {
"level": 1,
"currentExperience": 0,
"requiredExperience": 0,
"missingExperience": 0
},
"skins": [
"skin1",
"skin2",
"skin3"
]
}
},
"notifications": {},
"rewards": {}
}
Now i explain what the problems im having.
now if i have to change, for example, a property of a specific item that is inside inventory, i take the object "inventory" -> i look for the item i need and then i modify the property.
at the end of this, using an update operator "$set", i replace the "inventory" field.
This may be fine if you have very little data, but within that field there will be hundreds of "sub-field" and this seems like a useless waste resources.
Unfortunately, using $inc operator, i can not pass in any way "the path" of the property that i want to change.
could you help me?
here is what i do now
var userDoc = myCollection("userData");
var userData = userDoc.findOne({"userId": userId}, {items: 1, _id: 0});
//Other code
userData.inventory[itemName][propertyName] = //other code;
userDoc.update({"userId": userId},{"$set": userData});
Thanks,
Regards
If you want to update an embedded document, you can access it using dot notation.
For above document, to update "property1" of "item1" inside "inventory":
db.inventory.update({"userId":"h8566d9482gghffhtry565"},{"$set":{"inventory.item1.property1":"1"}})
the problem is that the "path" is dynamic, I do not know which item will be modified. is the user decide which properties of the items change, I found this solution:
var inc = {$inc: {}};
inc.$inc['inventory.'+itemName+"."+statName] = 1; // itemName and statName are variables created by user
userDoc.update({"userId": userId}, inc);
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle