using country code as array/object names? scoping issue? - javascript

could anyone help me with this please, used Canada as example:
var CA = {
name: "Canada Name",
iso: "CA",
percentage: "23.4",
color: getColor(23.4)
};
$(function() {
$('#world-map').vectorMap({
map: 'world_mill_en',
.
.
onRegionTipShow: function(event, wrap, code) {
wrap.html('hello ' + code); // working, outputs "hello CA"
console.log(CA.name); // working, outputs "Canada Name"
console.log(code.name); // not working - undefined
},
.
.
How can I use the "code" to refer to the variable (CA in this case)?
As I see code outputs a string but I just can not turn it to a form that works
Thx

You would need to further wrap your CA object in another object, something like this:
var langs = {
CA: {
name: "Canada Name",
iso: "CA",
percentage: "23.4",
color: getColor(23.4)
}
}
You can then access the properties of langs using bracket notation. So assuming code = 'CA' in your example:
onRegionTipShow: function(event, wrap, code){
wrap.html('hello ' + code); // = 'hello CA'
console.log(langs[code].name); // = 'Canada Name'
},

Related

Javascript printing things that are not inside the code

I have this code in my JS
var customer = {
name: "John Jack",
speak: function(){
return "my name is "+name;
},
address:{
street: '123 main st',
city: 'Pittsburgh',
state: 'PA'
}
}
document.write(customer.speak());
In my HTML i expected
my name is John Jack
But instead i got something really weird
my name is Peaks mirroring in a lake below, Stubai Alps, Austria
I have some theories that this is somehow connected to the Chrome extension i'm using called "Pixlr",but i don't see how my js code could connect to that.I tried changing variable name and speak to say,but it still prints the same thing.What's wrong?
replace name with this.name
var customer = {
name: "John Jack",
speak: function() {
return "my name is " + this.name;
},
address: {
street: '123 main st',
city: 'Pittsburgh',
state: 'PA'
}
}
document.write(customer.speak());

How to parse a Non-Json data hemera

I am new to Json and JavaScript. Currently I have a url which returns a JSON response. But the problem is that, It is not in correct format. Please see my response below
var pd={ player:
{ id: 363609002,
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
dateCheck: 1487204427149,
dateUpdate: 1474581052618,
dateCreate: 1384980182606,
dateStreak: 1474581052618,
lastDay: '20160715',
country: '',
countryName: null,
rank:
{ nr: 121,
imgLarge: 'bf4/ranks/r121.png',
img: 'r121',
name: 'Major General II',
needed: 16110000,
next:
{ nr: 122,
imgLarge: 'bf4/ranks/r122.png',
img: 'r122',
name: 'Major General III',
needed: 16750000,
curr: 16720600,
relNeeded: 640000,
relCurr: 610600,
relProg: 95.40625 } },
score: 16724643,
timePlayed: 1476950,
uId: '2832665149467333131',
uName: 'm4jes',
uGava: '721951facb53ed5632e196932fb6c72e',
udCreate: 1319759388000,
privacy: 'friends',
blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
editable: false,
viewable: true,
adminable: false,
linked: false },}
from the above response I have to get the output as :
{
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
score: 16724643,
timePlayed: 1476950
}
By which method I can get the required out in Javascript
First of all the URL is not returning a JSON response but a JS object literal. The difference is explained here.
You have to get the string from the url. You can use the jQuery method get():
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
//Insert the rest of the code here
});
</script>
Then, jqxhr.responseText is the string which correspond to the object we want. With eval, we transform the string into an object:
pd = eval(jqxhr.responseText);
So here we have an object literal with all the pairs name/value. You can access the values you want by using the dot notation. If you want to get the name of the game for example, you can write this:
pd.player.game
So this leads to :
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
Then, you have to transform this JS object literal into a JSON by using the JSON.stringify() method:
console.log(JSON.stringify(myNewObject, null, '\t'));
It returns what you want:
{
"game": "bf4",
"plat": "pc",
"name": "m4jes",
"tag": "BPt",
"score": 16724643,
"timePlayed": 1476950
}
So here is the full code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
pd = eval(jqxhr.responseText);
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>

How to add array items in javascript?

In a wordpress plugin, there is a field box called 'data' where I can add code for it to pull, below in the code where it says 'data =' that is me referencing the box. In the box:
What I put in the field box entitled 'data':
{
contacts: [
{ name: "Name 1", email: "email1#test.com" },
{ name: "Name 2", email: "email2#test.com" }
]
};
This is what I put in the global field box, for it to apply to everything.
function (jQueryPopoverObj, mapObject, mapsvgInstance) {
// "this" = clicked mapObject
if(this.mapsvg_type == "region"){
return '<b>'+this.id+'</b>' +
this.data.contacts.map(function(contact) {
return contact.name + '<br>' +
'' + contact.email + ''
}).join('<br>');
} else if (this.mapsvg_type == "marker"){
return 'Marker - <b>'+this.id+'</b>, contact: '+this.data.email;
}
}
I want to also add { seat: "County Seat"} to the data portion and add it in the function.
I tried adding a line in the contacts, and then adding + '<br>' + contact.seat, after return contact.name, with no luck. Basically when it does the popover (which it pulls from global function for the template and the information from the data field box), I want it to have the CountySeat under the County Name (e.g. the County Seat for Harris County is Houston, so it would have Houston under Harris County).
Example of Lubbock County without the City name under it
var data = {
contacts: [
{ name: "Name 1", email: "email1#test.com" },
{ name: "Name 2", email: "email2#test.com" }
]
}
To add a new property seat you can simply do this-
data["seat"] = "County Seat"
or
data.seat = "County Seat"
JSFiddle
It looks like you want to set the seat assignment on the contact? You'd have to get the contact from the array, looping through each one and figuring out the one you want to use, then do contact.seat = "XYZ", which will add a seat property to the contact object. You can then use contact.seat in the string output but you have to null check it because it may be null. To help with that, I'd recommend defaulting it to an empty string like:
data = {
contacts: [
{ name: "Name 1", email: "email1#test.com", seat: "" },
{ name: "Name 2", email: "email2#test.com", seat: "" }
]
}
And then change it when it is assigned.

Javascript: unique location.href

Hi,
I am currently working on this autocomplete-searchbox, and as untutored I am when it comes to JavaScript i wonder: how do i give each value an specific unique link to another .html page? So that 'Desserts' links to page1.html & 'Snacks' to page2.html?
As you can see are all the values currently linking to location.href = "http://www.cnn.com"; but i want to give each value a specific location.href..
Best regards
$(function(){
var term = [
{ value: 'Desserts' },
{ value: 'Snacks'},
{ value: 'Drinks'},
{ value: 'Cheesecake'},
{ value: 'Cookies'},
];
$('#autocomplete').autocomplete({
lookup: term,
onSelect: function myFunction() {
location.href = "http://www.cnn.com";
}
});
});
I think this is the direction you want to head. If you post more of what you have I can give you a more specific answer
$(function(){
var term = [{
value: 'Desserts',
location: 'page1.html'
},{
value: 'Snacks',
location: 'page2.html'
}, {
value: 'Drinks',
location: 'page3.html'
}, {
value: 'Cheesecake',
location: 'page4.html'
}, {
value: 'Cookies',
location: 'page5.html'
},];
$('#autocomplete').autocomplete({
lookup: term,
onSelect: function myFunction(e) {
//Depending on how you trigger onSelect e.currentTarget.location
//may or may not work. but you should be able to start with e
//and work your way to finding location.
location.href = "http://www.cnn.com"+e.currentTarget.location;
}
});
});
Also you could look into a library with a built in autocomplete and the documentation that goes with it. JQuery have something you could look into here: http://jqueryui.com/autocomplete/#combobox

javascript object literals using it's own fields

I would like to create ONE object containing the whole config for certain component. I would liek it too be like this:
var ObjectConfig = {
fieldKeys : {
name: "Obj. name",
state: "Obj. state",
color: "Obj. color"
},
templates : {
basicTemplate : [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
altTemplate : [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
}
}
But this in the right way to do it - it doesn't work. How can I achieve my goal?
EDIT:
Sorry, I was writing it by hand in a hurry, that's where the syntax errors came from. Now it's correct. The error I get is Uncaught TypeError: Cannot read property 'fieldKeys' of undefined. I guess that doing it this way is impossible - what is the best alternative then?
Your problem is that the object is constructed from the literal before it is assigned to the ObjectConfig variable. Therefore, accessing ObjectConfig.fieldKeys inside the literal will lead to the error.
The best solution is to construct first one object only, and then add further properties sequentially:
var ObjectConfig = {
fieldKeys: {
name: "Obj. name",
state: "Obj. state",
color: "Obj. color"
}
};
ObjectConfig.templates = {
basicTemplate: [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
altTemplate: [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
};
Another (shorter) method would an extra variable for the keys object, which is assigned before the construction of the templates object:
var keys, ObjectConfig = {
fieldKeys: keys = {
name: "Obj. name",
state: "Obj. state",
color: "Obj. color"
},
templates: {
basicTemplate: [ keys.name, keys.state ],
altTemplate: [ keys.name, keys.color ]
}
};
To work around the extra variable in global scope, you might use an IEFE. A more readable solution might look like this then:
var ObjectConfig = (function() {
var keys = {
name: "Obj. name",
state: "Obj. state",
color: "Obj. color"
};
return {
fieldKeys: keys,
templates: {
basicTemplate: [ keys.name, keys.state ],
altTemplate: [ keys.name, keys.color ]
}
};
})();

Categories