function test(results) {
//Populate the ComboBox with unique values
var Gov;
var values = [];
var features = results.features;
var og;
for (i = 0; i < features.length; i++) {
var aGOV = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, aGOV);
var cbx = document.getElementById("cbxGov");
cbx.options.add(og);
}
}
function gov_selection_change()
{
var cbx = document.getElementById("cbxGov");
var itm = cbx.options[cbx.selectedIndex].value.hasOwnProperty("Shape");
}
html code
<select id="cbxGov" onchange="gov_selection_change()">
My problem is i m not able to access property of aGOV in my gov_selection_change() function, it shows it has no such property, itm is false.
The value property of an HTMLOptionElement always returns a DOMString (a.k.a. text), not an object.
So you have to save what you want to access in a lookup dictionary and then use the returned value as a lookup key.
var lookupDictionary = {};
function test(results) {
var lookupKey,
og;
//...
// don´t get the element in the loop
var cbx = document.getElementById("cbxGov");
//...
for (i = 0; i < features.length; i++) {
lookupKey = features[i].attributes.GOV_NO;
lookupDictionary[lookupKey] = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, lookupKey );
cbx.options.add( og );
}
}
function gov_selection_change() {
var cbx = document.getElementById("cbxGov");
var key = cbx.options[cbx.selectedIndex].value;
var itm = lookupDictionary[key].hasOwnProperty("Shape");
}
The variable aGOV is only available in the context of your result() function. If you want to use it from a different function declare it as a global variable.
Example:
var aGOV;
function result()
{
// initialize aGOV
}
function gov_selection_change()
{
// now you can access the aGOV variable
}
Related
I'm trying to filter in an array by data in another array using concat in a for loop. The elements of the following code are logging correctly, but the final array is logging an empty array.
function Shipments (){
var app = SpreadsheetApp;
var movementSS = app.getActiveSpreadsheet();
var infoSheet = movementSS.getSheetByName("Update Info");
var orderInfoSheet = movementSS.getSheetByName("Order Info");
var targetSheet = movementSS.getSheetByName("Shipments");
var ShipLogSS = app.openByUrl(URL).getSheetByName("Shipping Details");
var ShipArr = ShipLogSS.getRange(3,1,ShipLogSS.getLastRow(),ShipLogSS.getLastColumn()).getValues().
filter(function(item){if(item[1]!=""){return true}}).
map(function(r){return [r[0],r[1],r[2],r[4],r[10],r[11],r[16],r[18],r[23]]});
var supplierData = orderInfoSheet.getRange(3,6,orderInfoSheet.getLastRow(),1).getValues().
filter(function(item){if(item[0]!=""){return true}});
var supplierList = [];
for (var i in supplierData) {
var row = supplierData[i];
var duplicate = false;
for (var j in supplierList) {
if (row.join() == supplierList[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
supplierList.push(row);
}
}
var supplierFilter = [];
for(var i = 0; i < supplierList.length; i++){
var shipments = ShipArr.filter(function(item){if(item[4]===supplierList[i][0]){return true}});
supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);
}
Any help would be greatly appreciated!
You need to assign the result of concat onto the supplierFilter in order to see the changes in later iterations and in the outer scope.
You can also return the comparison done inside the .filter callback immediately, instead of an if statement - it looks a bit cleaner.
var supplierFilter = [];
for (var i = 0; i < supplierList.length; i++) {
var shipments = ShipArr.filter(function (item) { return item[4] === supplierList[i][0]; });
supplierFilter = supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);
So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)
I'm trying to auto increment a properties value each time I instantiate a new instance of the class. This is what my class constructor looks (I abstracted it down just a bit):
var Playlist = function(player, args){
var that = this;
this.id = ?; //Should auto increment
this.tracks = [];
this.ready = false;
this.unloaded = args.length;
this.callback = undefined;
this.onready = function(c){
that.callback = c;
};
this.add = function(tracks){
for(var i = 0; i < tracks.length; i++){
this.tracks.push(tracks[i]);
this.resolve(i);
}
};
this.resolve = function(i){
SC.resolve(that.tracks[i]).then(function(data){
that.tracks[i] = data;
if(that.unloaded > 0){
that.unloaded--;
if(that.unloaded === 0){
that.ready = true;
that.callback();
}
}
});
};
player.playlists.push(this);
return this.add(args);
};
var playlist1 = new Playlist(player, [url1,url2...]); //Should be ID 0
var playlist2 = new Playlist(player, [url1,url2...]); //Should be ID 1
I'd like to not define an initial variable that I increment in the global scope. Could anyone hint me in the right direction? Cheers!
You can use an IIFE to create a private variable that you can increment.
var Playlist = (function() {
var nextID = 0;
return function(player, args) {
this.id = nextID++;
...
};
})();
You can set Playlist.id = 0 somewhere in your code, then increment it in the constructor and assign the new value to the instance property, as: this.id = Playlist.id++.
This suffers from the fact that it is not well encapsulated, so it could be misused.
Otherwise, I was to propose the solution described by Mike C, but he already set a good answer that contains such an idea, so...
I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:
I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);