Global variables to pull from an associative array/object? - javascript

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

Related

How to add an object as a data attribute

Using the api I was able to retrieve the info i needed trough the following endpoints and create the following object.
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
}
<datagrid id = "topicGrid" data='[{}]'>
<datagrid-column head="Topic" content-key="name"></datagrid-column>
<datagrid-column head="Followers" content-key="followers"></datagrid-column>
<datagrid-column-time head="Created" content-key="created" format="date"></datagrid-column-time>
<datagrid-column-time head="Updated" content-key="updated" format="date"></datagrid-column-time>
</datagrid>
I would like to somehow append the "lego" object in the new data attribute ?
Now i tried something like
setAttribute("data", lego); but my knowledge here is limited.
Any help is apreciated. Thank you.
Update:
I tried passing the object as a string but I only get the last element of the object. Kind of like it's looping trough the whole object and stopping at the last one.
$('datagrid').attr('data', JSON.stringify(lego));
My solution
$.get( "..." ).done(function( data ) {
var legoArr = []
$.each(data.topics, function(index,item) {
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
};
legoArr.push(lego);
});
$('datagrid').attr('data', JSON.stringify(legoArr));
});

Access js object using variable

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/

The JSON parsed into HTML, how objects are mapped to corresponding HTML?

For example, the following JSON:
{
"A" : [{
name : "admin",
email:"xxx#msn.com"
},{
name : "anly",
email:"xxx#msn.com"
}]
"B" : [{
name : "beta",
email:"xxx#msn.com"
},{
name : "b",
email:"xxx#msn.com"
}]
}
Html formatted as follows:
<ul>
<li>admin</li>
<li>anly</li>
<li>besta</li>
<li>bestb</li>
</ul>
How By clicking li, found to their corresponding object?
I think the method is:
1, by traversing JSON find, but this way is time-consuming, not simple
2, which is bound to the data key and index attributes above and through the key index to find, but if some of the more complex data structures, as too cumbersome, and do not know that there is no other better way to achieve it?
The above content is translated through Google, I do not know whether a clear description of my problem?
Here are two examples of what I wrote myself realized:
http://jsfiddle.net/18q41mfr/
It all depends on your requirements. How large will this JSON object be and how frequently will it change?
For small or constantly changing JSON objects, it might be just fine to do the method 1.
For large and constant JSON objects, go with method 2. A cleaner way to achieve method 2 that you've suggested is to make use of the Underscore.js values and groupBy method.
Merge all values in your object with the var merged = _.values(object)
Group by name var formatted = _.groupBy(merged, 'name');
Resulting JSON is such:
{
admin: {
name : "admin",
email:"xxx#msn.com"
},
anly: {
name : "anly",
email:"xxx#msn.com"
},
...
}
Use the following code to get the value in your onclick event function on your li element:
formatted[this.innerHTML].email
It seems that you're already using jQuery; you can simply stuff the object references into your HTML elements using .data().
Internally, an object reference map is maintained and the HTML element stores the reference key in a special property name.
var items = {
"type_a" : [{
name : "test",
color : "red"
},{
name : "test",
color : "blue"
}],
"type_b" : [{
name : "test",
color : "orange"
},{
name : "test",
color : "yellow"
}]
};
for (var i in items) {
for (var j = 0; j < items[i].length; j++) {
$('<li>', {text: items[i][j].name})
.data(items[i][j])
.appendTo('#items');
}
}
$("#items").on("click", "li", function() {
var obj = $(this).data();
$("#detaila").html('name:' + obj.name + '<br>color:' + obj.color + '<br>' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="items"></ul>
<div id="detaila"></div>
<div id="detailb"></div>
Your second method is kind of good enough.
Maintain a global object myObjs for searching, whose keys are name and the values are object itself.
For each of the objects like:
var obj = {
name : "beta",
email:"xxx#msn.com"
}
myObjs[obj[name]] = obj; // If the name is not unique, add an id.
Then bind the key to the HTML element:
<li data-key="admin">admin</li>
When the element is clicked, find the key, query myObjs and find the obj. Something like (assume you are using jQuery):
$('ul').on('click', 'li', function() {
var $this = $(this);
var name = $this.data('key');
var obj = myObjs[name];
console.log(obj); // Here is your corresponding object.
});
Cons: extra memory
Pros: fast.

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]);
});

Categories

Resources