JavaScript: Convert string to value of predefined variable - javascript

I have a JavaScript object that looks like the following:
venue = function(map, dataSet) {
// set some constants
this.VENUE_ID = 0;
this.VENUE_NAME = 1;
this.VENUE_CITY = 2;
this.filterBy = function(field, value) {
...
var filterValue = 'parent.VENUE_' + field;
}
}
Now, the problem is that I need the value of filterValue to contain the value of the constant on the parent object. Currently I have tried using the method shown above and then referencing the filterValue when trying to access the array item, but this simply returns undefined.
How do I convert the filterValue variable into the value of the constant it represents?

This has nothing to do with the variable scope.
var filterValue = this['VENUE_' + field];
would do.

JavaScript has no concept of 'parent'. And I think you're confusing scope and context. If that method was written as var filterBy() you'd have to access it in a different 'scope'. But by using 'this' you kept in in the same object as it was written. So everything you wrote is in 'this' context.

Try this:
var filterValue = this['VENUE_' + field];

Related

Determine if value exists in JavaScript "hash table"

I have built a JavaScript object that functions as a hash table.
var hashTable = {};
The table consists of key value pairs that are manually built. The table will be used to generate a new value based on an old value, or key, in the table.
//hashTable['old_value'] = new_value;
hashTable['115004568543'] = 115004567503;
hashTable['115004545983'] = 360000857366;
hashTable['115004723526'] = 360000865566;
hashTable['115004723646'] = 360000865566;
I have another variable that is compared to the keys in the hash table. If it matches a key in the hash table, then it can be used to capture the new value mapped to it.
For example, let's say some_value is declared.
some_value = '115004568543';
Since it matches a key value (or old_value) in the hash table, I can get the new value by calling
var new_value = hashTable[some_value];
// new_value is going to be equal to 115004567503 due to the mapping above
My problem is that I have two different hash tables that "some_value" is being compared against. I want to see if the first value in the hash is present either in the first hash table OR in the second hash table. So I have been working with:
var hashTable = {};
hashTable['115004568543'] = 115004567503;
hashTable['115004545983'] = 360000857366;
var hashTable2 = {};
hashTable2['115004702483'] = 360000857366;
hashTable2['115004560766'] = 360000857366;
var some_value = '115004545983';
if (hashTable.includes(some_value)) {
var new_value = hashTable[some_value];
//Do some other stuff with new_value
}
else if (hashTableTwo.includes(some_value)) {
var new_value = hashTableTwo[some_value];
//Do some other stuff with new_value
}
Additionally, some_value will exist in the first hash table, the second hash table, or not at all. It will not exist multiple times.
MY QUESTION: I am trying to use hashTable.includes() to see if some_value is present in either of the two hash tables. It isn't working. What is the best way to determine if some_value is a value in one of the hash tables?
When I try to call hashTable.includes(some_value) I get
Uncaught TypeError: hashTable.includes is not a function
Array.includes() is an array method. Since your hashtable is based on an object, it doesn't support this method.
If your values aren't falsy (false, undefined, null, 0, NaN) you can use logical short-circuit evaluation to assign the value:
var new_value = hashTable[some_value] || hashTableTwo[some_value] || some_value;
If they might be falsy, you can use the in operator to check if they exist in the object:
if (some_value in hashTable) {
var new_value = hashTable[some_value];
} else if (some_value in hashTableTwo) {
var new_value = hashTableTwo[some_value];
//Do some other stuff
}

Assign value of variable from JS array based on key

I have a variable that takes its value from the current object's ID attribute, it will always look something like filtercolor-red:
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = $(this).attr('id');
...
});
I also have an array that lists possible ID's and a corresponding HEX code:
var activeFilterBg;
var filterBgColor = [];
filterBgColor = {
filtercolor-black: '#171710',
filtercolor-blue: '#4C94B6',
filtercolor-brown: '#50443D',
filtercolor-gold: '#F6D069',
filtercolor-green: '#96B14D',
filtercolor-grey: '#A8AAA5',
filtercolor-orange: '#DB5E46',
filtercolor-pink: '#E78EB1',
filtercolor-purple: '#59547E',
filtercolor-red: '#D22200',
filtercolor-silver: '#EBEBEB',
filtercolor-white: '#FFF'
};
What I'd like to do is take filterColor and assign activeFilterBg the appropriate HEX code from filterBgColor. I could do this with a switch, but that seems kind of sloppy and gives a lot of room for mistakes in the future.
Do I have an option to somehow lookup the correct key and then assign a variable based upon it?
That's not an array, that's an object. You assign an array to the variable, but then you immediately replace that with an object. An object works well for this, so just skip that array. (Note though, as Jordan pointed out, that the parameter names has to be quoted when they contain dashes.)
You can use the bracket syntax to access the object properties using the variable:
var activeFilterBg;
var filterBgColor = {
'filtercolor-black': '#171710',
'filtercolor-blue': '#4C94B6',
'filtercolor-brown': '#50443D',
'filtercolor-gold': '#F6D069',
'filtercolor-green': '#96B14D',
'filtercolor-grey': '#A8AAA5',
'filtercolor-orange': '#DB5E46',
'filtercolor-pink': '#E78EB1',
'filtercolor-purple': '#59547E',
'filtercolor-red': '#D22200',
'filtercolor-silver': '#EBEBEB',
'filtercolor-white': '#FFF'
};
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = $(this).attr('id');
activeFilterBg = filterBgColor[filterColor];
});
Check the object first with hasOwnProperty - and if the property exists, use it!
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = this.id; //$(this).attr('id');
var color;
if (filterBgColor.hasOwnProperty(filterColor) {
color = filterBgColor[filterColor];
} else {
color = "#FFF"; //not found
}
});
mapping the id to the color should be as simple as
var filterColor = $(this).attr('id');
var hexCode = filterBgColor[filterColor];
//then do whatever with the hexCode

Create a multiple object with dynamic names

I created a function which allows to return an object whose name change to each loop.
I done this function like this :
function createObjPack(index){
var currentPack = packVehicule[key].libelle;
return [eval(currentPack + ' = {}' ), calcul(currentPack, key)];
};
The variable curentPack contains the name of the current object.
The return must generate a object which name match the value of currentPack
I thought read the currentPack directly into an eval() function for change dynamicly the name but, it doesn't work.
Someone can help me ?
Don't use dynamic variable names, use an object.
var packs = {}
function createObjPack(index) {
var currentPack = packvehicule[index].libelle;
var newPack = {};
packs[currentPack] = newPack;
return [newPack, calcul(currentPack, index)];
}

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

JavaScript: Why isn't my closure working?

The following code is only assigning the value of the last .enter_form input to the last MYAPP.list[0].responses[MYAPP.score.round].form[key] (where key is the only thing that varies). I think it's because only the last value of the key is being passed to addEntry(), but I can't figure out how to get around that.
$('.enter_form input').each(function() {
var key = $(this).attr('id');
var val = $(this).val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form = [];
function addEntry() {
return function(k) {
MYAPP.list[0].responses[MYAPP.score.round].form[k] = {'entry': userDict[k]};
}(key);
}
addEntry();
}
Your addEntry function is redundant since each iteration is already run inside it´s own scope so key and val are preserved properly (hope that explanation makes sense). Also the array you where inserting into was overwritten each iteration as well, so at the end of the .each() you end up with an array with only 1 value. It should also be an object rather then an array, even if the id's are numerical.
// you where overwriting this each iteration
MYAPP.list[0].responses[MYAPP.score.round].form = {};
$('.enter_form input').each(function() {
var el= $(this); // cache instead of creating a new jQuery object each time
var key = el.attr('id');
var val = el.val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form[key] = {'entry': userDict[key]};
}); // ); was also missing
Should work.
It's a bit hard to work out what it's meant to do, but I think this is probably it:
MYAPP.list[0].responses[MYAPP.score.round].form = [];
$('.enter_form input').each(function() {
var $this = $(this),
key = this.id,
val = $this.val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form[key] = {
'entry': val
};
});
That's based on your saying that "...key is the only thing that varies" (presumably $(this).val() also varies, but I took your point). It will add entries to MYAPP.list[0].responses[MYAPP.score.round].form for each of the form's input ids, as well as adding them to the userDict map.
As a side note, if the id values on the input elements aren't purely numeric, then I suspect you want to start with a blank object:
MYAPP.list[0].responses[MYAPP.score.round].form = {};
// ^^-- change is here
...rather than an empty array:
MYAPP.list[0].responses[MYAPP.score.round].form = [];
...although since arrays are objects, it works even if you're adding non-numeric properties.
Off-topic: No need for $(this).attr('id'). Just use this.id.

Categories

Resources