I have been looking for the answer to this problem, but I haven't found exactly a similar issue.
I have created several objects (ob0, ob1, ob2) they all contain the same entries.. but on each object the value of the entries is different. i.e. ob0.brand has one value but oj1.brand has a different value.
I want to visualize the info of the objs on a website. there is a radio button that returns ob0, ob1, or ob2 accordingly to what is chosen.. and on one div class, the text content of the value of the entries is to be displayed.
the radio buttons value is named a var objSelc and try to use documentselctor to display ojbSelc.brand so that whatever the user selects would represent obj0.brand or obj1.brand etc. However, this returns an error.
Maybe it's not possible to use a var as the name of an object? or what workaround would there me??
btw I am a level 0.1 first month of learning, Any help will be appreciated.
here is the snippet of code in question:
so here is for example an inventory of a bike and the different components, brake pads, tires, chain etc. I have made different copies of these but replaced the content info.
let UA = {
brakes: "shimano b10s",
backTire: " Bigben 26",
frontTire: "bigben 20",
bikeChain: " 1/32 single speed",
motorBrand: " Bosch Intuvia, cargoline",
};
let cargoCarla = {
breaks: "shimano b10s",
backTire: "big apple 24",
frontTire: "big apple 20",
bikeChain: "na",
motorBrand: "na",
};
Here comes some user input from the radio buttons from the HTML site
var form = document.querySelector("form");
var log = document.querySelector("#log");
form.addEventListener(
"submit",
function (event) {
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
}
// log.innerText = output;
event.preventDefault();
var splitOut = output.split("=");
var bikeSelc = splitOut[1].toString();
showComponent.textContent = bikeSelc.brakes;
},
false
);
In fact, bikeSelc does produce either UA or cargoCarla depending on which was selected. but bikeSelc.brakes do not produce a result so JS is not reading the value of bikeSelc when added to.brakes. even though consel.log does give the proper variable.
showComponent.textContent = UA.brakes;
This was just me hardcodingto see what it would look like on the DOM
Related
What I want to do is change the url.
Replace the Object word with an event parameter called e1.
Replace the word field with the event parameter e2.
I know this code is not working.
But I don't know how to do it.
The following is my code that I just wrote.
function getAllFieldValue(e1,e2) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = 'test123.my.salesforce.com/services/data/v44.0/queryAll?q=SELECT Field FROM Object';
var url = url.replace('Object',e1);
var url = url.replace('Field',e2);
var response = UrlFetchApp.fetch(url,getUrlFetchOptions());
var json = response.getContentText();
var data = JSON.parse(json);
var fieldValues = data.records;
for(var i=0;i<fieldValues.length;i++){
var fieldValue = fieldValues[i].e;
ss.getRange(i+1,1).setValue(fieldValue);
}
}
I want to take the data from another database through this code and put it in the Google spreadsheet.
For e1, it means the object value selected in the dropbox.
For e2, it means the field of the object selected in the drop box.
Is there a way to use two event parameters for one function?
I look forward to hearing from you.
====================
Please understand that I am using a translator because I am not good at English.
Checking fieldValues[i] in Logger.log returns the following values:
[{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03VAAT
},
Name=University of Arizona
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03TAAT
},
Name=United Oil & Gas Corp.
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03ZAAT
},
Name=sForce
}]
The issues I am currently experiencing are as follows.
If I select 'Name' from the drop-down list, ec2 becomes 'Name'.
As far as I'm concerned,
var fieldName = fieldValues[i].e2 is
var fieldName = fieldValues[i].Name
It means that.
I think fieldValues[i].e2 should return the values of University of Arizona, United Oil & Gas Corp, sForce.
But in reality nothing is returned.
var fieldName = fieldValues[i].Name works properly.
I think there is a problem with fieldValues[i].e2
This is the problem I'm currently experiencing.
There was no problem with the parameters e1, e2, which I thought was a problem. The reason why the code did not work is because of the for loop var fieldValue = fieldValues[i].e; Because it didn't work properly.
var fieldName = fieldValues[i].e2
to
var fieldName = fieldValues[i][e2]
After modifying it like this, the code works properly.
What I'm trying to do is, dynamically create clickable links from user provided textarea data, first being saved to the local machine using localStorage. User data is provided in the following format:
a|aa,
c|cc,
e|ee,
a,c,e are the labels for the links
aa,cc,ee are the links themselves
example of final output:
<a href="aa" />a</a>
<a href="cc" />c</a>
<a href="ee" />e</a>
Step 1: Save data to localStorage in a format that will later be used to create 2 separate arrays.
This is what I've done so far for step 1 (not sure it's correct)
// remove white space and carriage returns
textToSave = textToSave.replace(/(\r\n|\n|\r)/g,"").trim();
// replace | from user data with =>
var textToSaveArrayFormat = textToSave.replace(/(\|)/g, "=>");
// store data to localSorage
localStorage.setItem("appLinkConfig" ,JSON.stringify(textToSaveArrayFormat));
Step 2: Retrieve data from localStorage and create 2 arrays from that data
URLLabels = ["a", "b", "c"];
URLOptions = ["aa", "bb", "cc"];
For step 2 I start with
// get local storage app link config data
var appLinksObj = JSON.parse(localStorage.getItem("appLinkConfig"));
console.log(appLinksObj);
which returns
a=>aa,c=>cc,e=>ee,
From this I need to create my 2 arrays and this is where I'm stuck.
Step 3: I'm currently doing this with hardcoded arrays in my script, but would like to do it with the array data created in step 1 and 2.
// Object created
var obj = {};
// Using loop to insert key
// URLOptions in Object
for(var i = 0; i < URLLabels.length; i++){
obj[URLLabels[i]] = URLOptions[i];
}
// Printing object
for (var URLLabels of Object.keys(obj)) {
lnk.innerHTML += "<a href=\'" + URLLabels + "' target\='" + hotDeck + "'\>" + obj[URLLabels] + "</a>";
}
hotDeck is a flag I'm using to target one of two frames (returns the ID of those frames) contained in the page.
Thanks in advance for your help - please be gentle, I've been away from coding for a long time due to illness and coding again now to help my recovery. I'd be very grateful to solve this problem.
I assume this is what you are expecting. try the snippet on the console as i am not able to aceess localStorage property in the code snippet
var input = 'a|aa, c|cc, e|ee';
var output = input.split(',').map(str => str.split('|'));
window.localStorage.setItem('appLinkConfig', JSON.stringify(output));
var config = JSON.parse(window.localStorage.getItem('appLinkConfig'));
var result = config.map(([text, href]) => `${text.trim()}`).join(' ')
console.log(result);
I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.
Alright so I stuck on the code reading docs.
Iam starting with JS so go easy one me =].
I've got and array calld Area
which contains few arguments
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights", ...];
I cannot change this array till specific part of my code is executed but after I wish to add to every position another value. How to I do that to get exacly like that :
let Area = ["Kanig Village 14:30", "Fort Chune 15:30", "Shadowy Heights 16:30", ...];
I THINK this is what you want to do:
https://jsfiddle.net/wxzrpjeL/
//Declare 2 arrays
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights"];
let b = ["1", "2", "3"];
//Execute a function for each element in the Area array
Area.forEach(function(val, i) {
//The function appends a space, and the corresponding element in the second array
Area[i] += " " + b[i];
});
// just to illustrate the result, throw the result to the screen as a string...
alert(Area.toString());
i hope this is your answer
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights"];
for(i=0;i<Area.length;i++)
{
var hour=14+i;
Area[i]+=" "+hour+" : 30";
}
I have this database, which looks like this
so the first keys are user uid taken from auth, and then the username he/she provided and what did they score for each match are taken also..
I just wanted to get each user total points - for example Ray total points is 45 and Wood total points is 44 but after looking through for the docs all I was able to do was just for one user, I have to write each user name and the specific match for each line to get the value.. now think of how it will be if they are dozens of users? hmm a lot of lines..
here is the JSON
the javascript code
var query = firebase.database().ref();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var Data1 = childSnapshot.child("Ray/Match1/Points").val();
var Data2 = childSnapshot.child("Ray/Match2/Points").val();
console.log(Data1 + Data2);
});
})
which will let me display, Ray total points, but not for Wood obviously I have to repeat it and write it..
So how do i solve this?
I took a look at your problem and I think I have your solution, or at the very least a PATHWAY to your solution. Ok, first I'll explain the basic issue, then I'll attempt to provide you with some generic-ish code (I'll attempt to use some of the variables you used). And away we go!
Basically what I see is 2 steps...
STEP 1 - You need to use a "constructor function" that will create new user objects with their own name (and/or user ID) and their own set of properties.
With that line of thinking, you can have the constructor function include properties such as "user name", "match points 1", "match points 2" and then a function that console logs the summary of each name and their total points from match points 1 and 2.
STEP 2 - You need to put the constructor function inside of a loop that will go through the database looking for the specific properties you need to fill in the properties needed by the constructor function to spit out the info you're looking for.
So... and let's take a deep breath because that was a lot of words... let's try to code that. I'll use generic properties in a way that I think will make it easy for you to insert your own property/variable names.
var user = function(name, match1, match2){
this.name = name;
this.match1 = match1;
this.match2 = match2;
this.pointTotal = function(match1, match2) {
console.log(match1 + match2);};
this.summary = function(){
console.log(name + " has a total of " + pointTotal + "
points.");};
}
the "This" part of the code allows ANY user name to be used and not just specific ones.
Ok, so the code above takes care of the constructor function part of the issue. Now it doesn't matter how many users you need to create with unique names.
The next step is to create some kind of loop function that will go through the database and fill in the properties needed to create each user so that you can get the total points from EVERY user and not just one.
Again, I will use generic-ish property/variable names...
var key = childSnapshot.key;
while(i = 0; i < key.length + 1; i++) {
var user = function(name, match1, match2){
this.name = name;
this.match1 = match1;
this.match2 = match2;
this.pointTotal = function(match1, match2) {
console.log(match1 + match2);};
this.summary = function(){
console.log(name + " has a total of " + pointTotal + " points.");};
}
}
That is a whole lot of words and the code is a hybrid of generic property names/variables and of property names/variables used by you, but I'm certain that I am on the correct pathway.
I have a lot of confidence that if you used the code and EXPLANATION that I provided, that if you plug in your own variables you will get the solution that you need.
In closing I just want to say that I REALLY hope that helps and if it doesn't I'd like to help solve the problem one way or another because I need the practice. I work a job with weird hours and so if I don't answer right away I am likely at my job :(
Good luck and I hope I helped!
simply add total node to your db
|_Id
|_ $userId:
| |_ Ray
| | |_ Match1:24
| | |_ Match2:21
| |_ total:45
and then get user`s total
var query = firebase.database().ref();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var total = childSnapshot.child("total").val();
console.log(total);
});
})
you can add the total node using cloud functions
Check out this implementation. No need for cloud function.
firebase().database().ref().on('value', function(snapshot) {
snapshot.forEach((user)=>{
user.forEach((matches)=> {
var total = 0;
matches.forEach((match)=> {
total += match.val().Points;
});
console.log(total);
});
});
})
If the key is the user's Id, why add yet another nested object with the user's name? Do you expect one user to have multiple usernames? That sounds weird and adds on complexity, as you have probably noticed. If you need to keep the user name somewhere in Firebase, it is recommended that you dedicate a user details section somewhere directly under the user Id key. Here is a JavaScript representation of the Firebase object structure:
{
a1230scfkls1240: {
userinfo: {
username: 'Joe'
},
matches: {
asflk12405: {
points: 123
},
isdf534853: {
points: 345
}
}
}
}
Now, getting to the total points seems a bit more straightforward, does it not? 😎
To help you without modifying your current database structure, all you need is to loop through all the userId+username+matches permutation in your database. Here is an example code to achieve just that, you do not need any special Firebase feature, just good old JavaScript for-of loop:
const query = firebase.database().ref();
query.once('value')
.then(snapshot => {
const points = {}
const users = snapshot.val()
for (const userId of Object.keys(users)) {
const userprofile = users[userId]
for (const username of Object.keys(userprofile)) {
const user = userprofile[username]
for (const matchId of Object.keys(user)) {
const match = user[matchId]
// Store the points per user, per profile, or per both, depending on your needs
points[username] = points[username] === undefined
? points[username] = match.points
: points[username] += match.points
}
}
}
})