Access js object using variable - javascript

I'm not sure if I'm correct with topic title, so sorry about that.
I've got JS object '_buildings', which structure looks like this:
_buildings : {
laboratory : {
exist : false,
value : 1000,
},
office : {
exist : false,
value : 500,
},
}
Is it possible to access object somehow using this method:
var chain = 'laboratory'; //it could be 'office' or any other building name
var value = _buildings.chain.value;
Point is, I need to access object param while using variable in chain. Is it possible?
JSFiddle: http://jsfiddle.net/3k5anjjj/

yes, use square bracket notation
var x = _buildings[chain].value;
Updated fiddle: http://jsfiddle.net/3k5anjjj/1/

Related

BackboneJS - get specific value from collection using _.max method

I want to get a specific value from a model inside a Collection. The Collection is sorted by ID (contest_id) which is served by the database and gets delivered as JSON. So, the JSON looks like:
data : [{
"contest_id" : "3",
"artist" : {
"artist_name": "some name",
"artist_cover" : "some image.jpg"
}
},
"contest_id" : "1",
....
}]
Now, I have glued something together:
var contestImage = _.max(this.collection.toJSON(), function(cnt){
return cnt.contest_id;
});
I get the highest contest_id, which is what I want but how do I proceed when I want to grab the image? and even display it?
Thanks in advance...
The max method should actually be available directly from your Backbone collection (although it's an Underscore method, it's mixed into Backbone's Collections), which means you can simplify your code a bit.
Something like this should do the trick:
var model = this.collection.max(function (cnt) {
return cnt.contest_id;
});
var contest_id = model.get('contest_id');
The first section returns the model you want, and the second gets the contest ID attribute.
To get the artist cover attribute, you can then convert it to JSON:
var artist_cover = model.toJSON().artist.artist_cover;
Or get the artist attribute from the model:
var artist_cover = model.get('artist').artist_cover;
This actually made it work:
var contestImage = _.max(this.collection.toJSON(), function(cnt){
return cnt.contest_id;
});
var latestImage = contestImage.artist.artist_cover;
Thanks for the answers though :-)

Access JSON values from variable

The click handler is accessing a data attribute on the element and setting a variable based on what is it, in this case 'option1'. I want to use the name of this variable to access a JSON object. But in the example it's returning 'undefined', as if it's looking for an array called 'thisOption'. How can I use this data attribute to bring back the correct JSON content?
// Note: thisOption returns "option1", which is correct.
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('name');
jq('#subscriptions .price').text(thisOption.monthly);
});
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
If option1 is in the global scope then you can access it via the window object with a dynamic key:
jq('#subscriptions .price').text(window[thisOption].monthly);
The [] notation allows you to use variable property or key names.
You can access the option1 like below
jq('#subscriptions .price').text(window[thisOption].monthly);
Because option1 is in global scope, you can access it like window.option1. When option1 is a value of some variable, then you should access like window[thisOption]
I made some structure so we can see it clearly, you can also check it in jsfiddle.net
Heres the url: http://jsfiddle.net/8hTrr/3/
HTML
test
<div id="subscriptions">
<p class="price"></p>
</div>
JS
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('option');
jq('#subscriptions .price').text(option1[thisOption]);
});

Call a javascript function dynamically

I have some functions defined inside a array like this.
checkInputType : function(sel){
alert($(sel).prop('type'));
},
checkSelect : function(el){
.......
},
.....
And I can call it like this options.checkInput($(this));. This is working.
Now I want to call any of those defined functions dynamically. So I have this array with the function names in it.
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
Now looping through all elements inside a form I want to call the right function for each element(elmType2Func array with element as a key and function name as a value).
var element = $(this).prop('tagName').toLowerCase();
I cannot call like this - options.elmType2Func[element]($(this));
I know this is not the right way to call this function. Can anybody help me with this.
You need to store functions, not their names:
var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};
http://jsfiddle.net/hmb25/
If the functions are already members of some object, like:
var options = {
checkInput: function() {...},
checkSelect: function() {...},
}
then you can keep strings in elmType2Func:
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
and use double indirection to refer to them:
var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];
gives you a reference to the function.
Rather than putting a string for the name put the function
var elmType2Func = {
'input' : checkInput,
'select' : checkSelect,
'textarea' : checkTextarea,
'submit' : function (arg) { ... }
};
options.elmType2Func[element]($(this));
That is accessing the property with the literal name elmType2Func on the object - you want to use bracket notation here as well:
options[elmType2Func[element]]($(this));
Alternatively, you might not use elmType2Func as a property name lookup table, but to look up the functions directly:
var elmType2Func = {
'input' : options.checkInput,
'select' : options.checkSelect,
'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));

Changing nested attribute with model.set in Backbone

I'm trying to do what I hope is a simple thing -- doing a model.set only on a sub attribute of the object.
Right now, I have a model that looks like this:
{
"attr1" : true,
"attr2" : this.model.get("username"),
"attr3" : $('#tenant_select').val(),
"attr_array": [
{
"id": "sub_1",
"state": "active"
},
{
"id": "sub_22",
"state": "not_active"
}
]
}
I want to be able to grab reach into myMode.attr_array.state and change the value. However, using .set I've only been able to change attributes on the first level, i.e. attr_array.
Is there an way to do this using model.set?
You can do it (I'm wondering why you didn't manage to do it). But you have to be careful:
var array = this.get('attr_array');
array[1].state = 'active';
this.set('attr_array', array);
What's the problem here? Your model holds a reference of the object. Therefore the last line is useless, it won't change anything at all. It's simply equivalent to:
this.get('attr_array')[1].state = 'active';
And you lose any internal stuff Backbone does when you use set.
So what to do? Clone your object:
var array = _.clone(this.get('attr_array'));
array[1].state = 'active';
this.set('attr_array', array); // will trigger 'change' and 'change:attr_array' events

Global variables to pull from an associative array/object?

I have 50 dots on a page, each individual divs. When I click one, I want to use the ID to pull values out of an array. I can get the ID but I'm having trouble using that value to get stuff out of my array. Perhaps a global variable problem? Not sure. Not even sure if this is the best way to handle multiple clicks that access multiple data. Any help is appreciated!
var location0 = {"name" : "Location 1", "image" : "image1.jpg"};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(thisLocation["image"]); //Returns "undefined"
});
Here's a fiddle.
I'd do it like this :
var locations = {
location1 : {"name" : "Location 1", "image" : "image1.jpg"},
location2 : {"name" : "Location 2", "image" : "image2.jpg"}
}
$('.dot').click(function(){
alert(locations[this.id].name);
});
​
FIDDLE
$(this).attr("id") returns a String "location0". If you want to use it you have to get an actual location0 variable, so you have to replace one of your code lines using eval() function. like this:
var thisLocation = eval($(this).attr("id"));
I would however recommend using a new array, where "location0" would be a key, then you would just need to access a key with a string like locations["location0"] and avoid using eval().
you need to access it like this:
var test = {
location0: {"name" : "Location 1", "image" : "image1.jpg"}
};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(test[thisLocation]["image"]); //Returns "undefined"
});
​
edit: this works
Also the reason why it doesn't work for you at first place is because thisLocation is a string, not an object it self, so you need to use brackets to access objects property by passing name. I just wouldn't advice

Categories

Resources