How do I access this array in backbone? - arrays

I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:
buildMyArray: function() {
var self = this;
var myArray = {};
window.myLibrary.getStuff('myParameter', function(myStuff) {
for (var myKey in myStuff) {
if (myStuff.hasOwnProperty(myKey)) {
var myValue = myStuff[myKey];
myArray[myKey] = myValue;
}
}
self.set({ myArray: myArray });
});
}
However, how can I access that array from other properties? In other words, I want to do something like this:
checkArrayStuff: function(arrayKey) {
//loop through myArray and check value for arrayKey.
//var myArray1 = self.get(myArray);
//var myArray2 = this.get(myArray);
//var myArray3 = myArray;
//var myArray4 = this.myArray;
//var myArray5 = self.get('myArray');
//var myArray6 = this.get('myArray');
var myArray7 = self.myArray;
var can = myArray7[arrayKey];
return can;
}
I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.

I guess you would have to do this
checkArrayStuff: function(arrayKey) {
return this.get('myArray')[arrayKey];
}

this.get('myArray') should work but it looks like your window.myLibrary.getStuff function is asynchronous. That means myArray won't be set until some time after buildMyArray returns. If you give us more context we can make a better recommendation of how to address this such as having buildMyArray call checkArrayStuff after it's done the .set(..) or having buildMyArray return a promise

Related

How do I get unique values after getRespondentEmail in google apps script?

I've been trying without success to get unique values from an array, after creating the array from getRespondentEmail in google apps script. I've tried to use the set method, the forEach etc for this and each time it returns an empty array or empty curly brackets. This is a sample of my code:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
var uniqueResponses = [...new Set(getEmails)];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
Logger.log(uniqueResponses);
}
Does anyone know what the problem might be? I'm stuck. Thank you so much.
In your script, how about the following modification?
Modified script:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
var uniqueResponses = [...new Set(getEmails)];
Logger.log(uniqueResponses);
}
In your script, when var uniqueResponses = [...new Set(getEmails)] is run, getEmails has no value. By this, your issue occurs. In this modification, var uniqueResponses = [...new Set(getEmails)] is used after getEmails has the values. By this, the duplicated values are removed.
Reference:
Set

How to change [] with {} in my array object

I retrieve this data from an API
{"city":"New York","type":["0","1","9"]}
I need to convert in this way:
{"type":{0:true,1:true,9:true},...}
I try with angular foreach in this way
var tmparr = [];
angular.forEach( $scope.path.type, function (value, key) {
tmparr.push(value + ":true")
});
$scope.checkfilters.type = tmparr
but in this way i have this result and it's not what i need
{"business_type":["0:true","1:true","9:true"]}
I don't know how to replace the [] with {} in my array
If I try to set var tmparr = {} I have undefined error in push function
Use bracket syntax
var tmparr = {};
angular.forEach( $scope.path.type, function (value, key) {
tmparr[value] = true;
});
$scope.checkfilters.type = tmparr;
You can loop through the type and then copy the values and assign it to true.
var original = {"city":"New York","type":["0","1","9"]};
var copy = {};
for(var i in original.type){
copy[original.type[i]] = true;
}
console.log(copy);
You can also use reduce with an object accumulator:
var data = {"city":"New York","type":["0","1","9"]}
const result = data.type.reduce((r,c) => (r[c] = true, r), {})
console.log(result)

ng-if only works when referencing var direct from service, instead of var in controller scope

I am trying to understand why my ng-if statement doesn't work when I reference a local variable in my controller that is assigned to a value from a service, but it works properly if assigned directly to the value from that service.
For example, this works:
<div class="map" ng-if="interactiveMap.mapService.esriLoaded">
<esri-map id="map1"
map-options="interactiveMap.mapOptions"
load="interactiveMap.load"
register-as="interactiveMap">
</esri-map>
</div>
with the following controller:
angular.module('tamcApp')
.controller('InteractivemapCtrl', function (map, config) {
var self = this;
self.map = {};
self.mapService = map;
self.mapOptions = {
basemap: 'mcgiStreet',
extent: config.globals.initialExtent,
sliderStyle: 'small'
};
self.load = function(){
map.getMap('interactiveMap').then(function(thisMap) {
console.log(thisMap);
self.map = thisMap;
});
};
});
But if I were to assign the "esriLoaded" var to a local var in the scope, like this:
<div class="map" ng-if="interactiveMap.esriLoaded">
<esri-map id="map1"
map-options="interactiveMap.mapOptions"
load="interactiveMap.load"
register-as="interactiveMap">
</esri-map>
</div>
Controller here:
angular.module('tamcApp')
.controller('InteractivemapCtrl', function (map, config) {
var self = this;
self.map = {};
self.esriLoaded = map.esriLoaded;
self.mapOptions = {
basemap: 'mcgiStreet',
extent: config.globals.initialExtent,
sliderStyle: 'small'
};
self.load = function(){
map.getMap('interactiveMap').then(function(thisMap) {
console.log(thisMap);
self.map = thisMap;
});
};
});
Then it doesn't work. The value for "esriLoaded" is always false (which is the default value for esriLoaded). It's like it isn't updating the value of self.ersiLoaded when the value gets updated in the "map" service. Here is the code for the "map" service, just in case folks need it to answer this question.
angular.module('tamcApp')
.service('map', function (config, esriLoader, esriRegistry, esriMapUtils) {
// AngularJS will instantiate a singleton by calling "new" on this function
var self = this;
self.esriLoaded = false;
self.lazyload = function() {
// Make a call to load Esri JSAPI resources.
// A promise is provided for when the resources have finished loading.
esriLoader.bootstrap({
url: config.globals.esriJS
}).then(function() {
// Set Loaded to be true
self.esriLoaded = true;
// DEFINE CUSTOM BASEMAP USED BY ALL MAPS
esriMapUtils.addCustomBasemap('mcgiStreet', {
urls: ['http://myhost.com/arcgis/rest/services/BaseMap/StreetMap/MapServer'],
title: 'MCGI Street Map',
thumbnailurl: ''
});
});
};
if (!self.esriLoaded) {
self.lazyload();
}
self.getMap = function(id){
return esriRegistry.get(id);
};
});
That is actually not because of angular, but because of JavaScript. map.esriLoaded is a boolean value, a primitive and thus not an object, which leads to your local self.esriLoaded not becoming a reference (as only objects can be referenced), but just a plain copy of the boolean value contained in map.esriLoaded.
A short example to make it more clear:
//Primitive
var a = 5; //primitive
var b = a; //b just copies the value of a
a = 6; //This will change a, but not b
conosle.log(b); //will print 5
//Object
var a = { someValue: 5 }; //a is now a reference to that object
var b = a; //b also becomes a reference to the object above
a.someValue = 1337; //will change the object a is referencing, thus also
//changing the object b is referencing, as its the same object
console.log(b.someValue); //will print 1337

How to convert object literal to function

Is there any dynamic way to convert/clone this object:
var object = {
a: 2,
b: function(){
return this.a;
}
}
Into this kind of function object:
function object(){};
object.a = 2;
object.b = function(){
return this.a;
};
Is this possible? how can I do so dynamically?
You can just copy everything, though I would use the prototype:
function toClass(obj) {
var func = function () {};
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
func.prototype[i] = obj[i];
}
}
return func;
}
A whole other question is how useful this actually is and whether there is a better solution to the underlying problem.
Fiddle: http://jsfiddle.net/pb8mv/
It is a little bit strange that you need such a thing. If I have to guess, I think that you have an object and you want to extend it. I.e. you want to create function based on that object, so you later create multiple instances of it. That's possible and here it is a little snippet showing how:
var object = {
a: 2,
b: function(){
return this.a;
}
}
var extend = function(obj) {
return function() {
return Object.create(obj);
}
};
var Class1 = extend(object);
var ob1 = Class1();
ob1.a = 10;
var Class2 = extend(object);
var ob2 = Class2();
ob2.a = 23;
console.log(ob1.b(), ob2.b());
The result of the script is
10 23

AS3 Fastest way to merge multiple arrays

I'm trying to write a function where I can specify any amount of array, and the return value will be an array containing the contents of all of the specified arrays.
I've done this, but it seems like a really slow and ugly way of doing it:
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
function merge(...multi):Array
{
var out:String = "";
for each(var i:Array in multi)
{
out += i.join(',');
}
return out.split(',');
}
trace(merge(ar1, ar2));
Is there an inbuilt and more efficient / nice way of achieving this? The result does not need to be in the same order as the input - completely unsorted is fine.
You can use concat.
If the parameters specify an array, the elements of that array are concatenated.
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
var ar3:Array = ['i','j','k','l'];
var ar4 = ar1.concat(ar2, ar3); // or: ar1.concat(ar2).concat(ar3);
To make a single array out of a 2 dimensional array you can use this function:
private function flatten(arrays:Array):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar4 = [ar1, ar2, ar3];
var ar5 = flatten(ar4);
You can also use varargs to merge multiple arrays:
private function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar5 = merge(ar1, ar2, ar3);
I don't know if this method is faster than using loops, but it is a (fancy) quick way to merge 2 arrays. (and it works in Javascript and Actionscript)
var arr1:Array = [1,2,3,4,5]
var arr2:Array = [6,7,8,9,10]
arr1.push.apply(this, arr2); // merge
// arr1.push.call(this, arr2); // don't use this. see comment below
trace(arr1) // 1,2,3,4,5,6,7,8,9,10
function merge(...multi):Array
{
var res:Array = [];
for each(var i:Array in multi)
{
res = res.concat(i);
}
return res;
}
Didnt try it, but something like this would help you.

Resources