I have a map of the US with all 50 states as clickable buttons, when the user clicks a state I want to display information about that state, calling on that state's array dynamically. Below is my own weak attempt that obviously does not work.
var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC","DC2","DE","FL","GA","GU","HI","IA","ID",
"IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
"OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY");
function listenerForI( i ) {
document.getElementById(stateList[i])
.addEventListener('mousedown', function() {
stateSelect(stateList[i]);
}, false);
}
for (var i = 0; i < stateList.length; i++) {
listenerForI( i );
}
var HIdat = new Array(20,28,50,2) //one array for all 50 states COdat, AKdat, etc.
function stateSelect(state){
var display_data1 = state + "dat[0]";
alert(display_data1);
}
Should I use eval()? I've heard of something you can do with a global "window[]" but I don't understand how that would work.
You should store the state arrays in their own object:
var stateData = {
HI: [1, 2, 3],
IL: [4, 5, 6],
...
};
var myData = stateData[state];
Using window is an option, like this:
window[state + "dat"] will get you the array.
But I would suggest ... exactly what SLaks just posted, so do that instead.
In JavaScript, global vars are members of the window object, so you can use the array indexing syntax to get at them without using eval, which is generally to be avoided, like so:
function stateSelect(state) {
var display_data1 = window[state + "dat"];
alert(display_data1);
}
Related
I am trying to get load a variable from a array variable for my project but the value comes back as undefined I just used the console.log for the test output.
I want to learn how to use it after seeing others use on their projects and I want to do it to make my projects easier to manage.
I set it to trigger when the page loads up first thing.
Any help is welcome from the community.
My code if it helps solve it problem:
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values.odds_base)
});
In this case I think you have to use an object like this one, instead of array:
window.addEventListener('load',function() {
var values = {
odds_base: 10,
start_cash: 50
};
console.log(values.odds_base);
});
You are using the wrong data structure here. Square brackets are used for arrays. You should use a javascript object here.
window.addEventListener('load',function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Or you can do like this
let values = {};
values.odds_base = 10;
values.start_cash = 50;
console.log(values.odds_base);
If that is array then you have to use variables like this
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values);
console.log(odds_base);
console.log(start_cash);
});
When you assign array like this then Internally JavaScript first Creates the variable and then assign those variables in array
Otherwise convert that array to object and do like as follows
window.addEventListener('load',function(){
var values = {
odds_base : 10,
start_cash : 50
}
console.log(values);
console.log(values.odds_base);
console.log(values.start_cash);
});
The value of values looks like it should be an object and not an array as seen in your example i.e. values = [ a = 1, b = 2 ] should be values = { a: 1, b: 2 }
window.addEventListener('load', function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Tip: Declare the values variable outside the scope of the addEventListener callback if you wish it to be accessible outside also.
I have an array of JavaScript objects
var arrayObjs = [
{ id:abc123, radius:5.0},
{ id:def235, radius:2.5},...]
I have been using a for loop to find a particular object with id = def235, would it be more efficient to use an object like
var objectObjs = {
{ abc123:{ id:abc123, radius:5.0}},
{ def235:{ id:def235, radius:2.5}},...}
would it be more efficient to use an object like
If you're looking up by id, yes, almost certainly, but your example has an extra layer of {} you'll want to remove:
var objectObjs = {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
};
JavaScript objects are highly-optimized for property retrieval by name.
Another option is to use a Map, which is also optimized for retrieval by key.
If you use an object, probably best to create it via Object.create(null) so it doesn't inherit Object.prototype properties. You probably aren't going to look up ids like toString or valueOf, but still... :-) So perhaps:
var objectObjs = Object.assign(Object.create(null), {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
});
It's also trivial to create that object from your array, to avoid typing the ids twice and the opportunity for error that introduces:
var arrayObjs = [
{ id:abc123, radius:5.0},
{ id:def235, radius:2.5},/*...*/];
var objectObjs = Object.create(null);
arrayObjs.forEach(entry => { objectObjs[entry.id] = entry; });
Just for fun, I tried it: https://jsperf.com/accessor-test-loop-vs-object
Of course, as T.J. described - access by an object property is much faster. Interestingly, on Chrome the difference is much greater than on Firefox as I just tried out. Try to run the test of Chrome and Firefox or Edge.
var arrayObjs = [
{ id:'abc123', radius:5.0},
{ id:'def235', radius:2.5}
];
for (var i = 0; i < arrayObjs.length; i++) {
if (arrayObjs[i].id == 'def235') {
// found it
break;
}
}
..VS..
var objectObjs = {
abc123:{ id: 'abc123', radius: 5.0},
def235:{ id: 'def235', radius: 2.5}
}
var found = !!objectObjs.def235;
if (found) {
// ..
}
I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})
I am trying to do the following, where foo is a function which fills the 'out' array.
But for each data centre in data centres object, pushed out array is getting overwritten by a new value.
I want to prevent this overwriting.
How to create a new array reference/ instance in a loop?
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(out);
});
Put your out declaration outside:
var out = [];
_.map(datacenters, function(datacenter){
foo(datacenter, out);
$scope.dcSelected.push(out);
});
I don't fully understand what you trying to do, so I will do a general example:
var datacenters = [1,2,3,4]
var out = []
datacenters.map(function(datacenter){
datacenter2 = datacenter + 1;
out.push(datacenter2);
});
console.log(out);
[ 2, 3, 4, 5 ]
(I used map that way because I haven't imported the underscore for js)
You may try angular.copy(out) of angularJs. Hope it ll work for you
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(angular.copy(out));
});
You have 2 options:
1) create a closure
2) create another array as part of your controller, that will store linkage of data center and out an array, imagine it as a key, value but in a global variable of the same controller.
I have array of objects named tickets and I want to pick some specific objects from tickets like number,desc and state and assign them to new array of objects say myarr. I'm writing the below code but it says number is undefined. What am I doing wrong ?
$scope.myarr=[{
number:"",
desc:"",
state:""
}
];
for(var i=0;i<$scope.tickets.length;i++){
$scope.myarr[i].number=$scope.tickets[i].number;
$scope.myarr[i].desc=$scope.tickets[i].short_description;
$scope.myarr[i].state=$scope.tickets[i].state;
}
You need do something like this.
$scope.myarr=[];
for(var i=0;i<$scope.tickets.length;i++){
//Your Conditions
var object={
"number":$scope.tickets[i].number,
"desc" :$scope.tickets[i].short_description,
"state":$scope.tickets[i].state
}
$scope.myarr.push(object);
}
$scope.myarr = [];
angular.forEach($scope.tickets, function(ticket) {
this.push({number:ticket.number, state: ticket.state});
}, $scope.myarr);
If you don't need to support IE < 9, there is a handy function called map which is useful in this case
$scope.myarr = $scope.tickets.map(function(ticket) {
// return the element to be inserted in the new array
return {
number: ticket.number,
desc: ticket.short_description,
state: ticket.state
};
});