I have a JSON like:
var xx = {'name':'alx','age':12};
Now I can read the value of name which is 'alx' as xx[0].name, but how should I retrieve value of 'name' itself? By that, I mean how can I fetch the key at run time?
for (i in xx) {
if (xx[i] == "alx") {
// i is the key
}
}
modified Code (from Victor) taking into account that you might want to look for any other possible string
var search_object = "string_to_look_for";
for (i in xx) {
if (xx[i] == search_object) {
// i is the key
alert(i+" is the key!!!"); // alert, to make clear which one
}
}
You are looking for associative arrays in Javascript. A quick google search suggests the following:
Read this page http://www.quirksmode.org/js/associative.html
and especially this section http://www.quirksmode.org/js/associative.html#link5
Related
The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.
I am new on this website, and I am also new at Javascript.
What I would do is get a value from a link, eg:
http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741
I need to take this value: O=107905, if it is only one code I need to run a file (file A),
if it look like this: O=107905~107906, then I need to run a different file (file B).
What I thought is create a function with javascript where if it is (~) is missing, then will be used the file A, if there is one or more than one of (~) then the file B will start to work.
Many thanks in advance!
Well. We really do encourage you to provide your own code first before providing solutions, but this is a fairly simple problem in javascript. Here's my take on it.
The first problem you have to solve is actually getting the query string parameters in a meaningful format. Here I create an object that uses the query string keys as the object keys (IE 9+ only because of the forEach)
var tmpObject = {}
location.search.substr(1).split('&').forEach(function(item){
var o = item.split('=');
tmpObject[o.shift()] = o.shift();
});
Then it's just a matter of making sure the query string contained the target object (in this case "O") and determine if there is more than one.
if(tmpObject.hasOwnProperty('O') && tmpObject.O.split('~').length > 1) {
console.log('return multiple files');
} else {
console.log('return one file');
}
Try this
var url = "http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741";
var search = url.substring(url.indexOf("?")+1);
var map={};
search.forEach(function(val){var items=val.split("="); map[items[0]]=items[1];});
if (map["O"].indexOf("~") != -1)
{
//O value has ~ in it
}
else
{
//O has no ~ in it
}
Possible solution to get the paramter would be there : How to get the value from the GET parameters?
Once you have the parameter value, you can for sure look if you find '~' with String.prototype.indexOf.
String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.
This may be really simple, but I've beat my head against the wall trying to figure it out.
I need to grab a value from a JSON response, but the key returned in the response is random, so I can't directly reference it to drill into it.
Here's the response I'm getting back:
var c = {
"success": {
"7d40ab5352b0471cae5bdefc2e032840": {
"__type__" : "user",
"__id__" : "7d40ab5352b0471cae5bdefc2e032840"
}
},
"errors": {}
}
What I need is the random string you see there - the ID. I've tried all kinds of things, and cannot for the life of me figure out how to get the ID back as a string. I've tried getting at it with array notation c.success[0][0] to no avail. Obviously, I can't use dot notation, since I don't know what to put after .success.
Anyone know what to do in a situation where the keys of the array aren't known beforehand? I want to make sure that I do this in a way that's considered the best practice, not a hack.
Thanks...and if I've somehow missed an answer to this that's otherwise published, please send me that way. I've searched for days and can't find this answer.
This:
var obj = c.success[ Object.keys( c.success )[0] ];
obj.__type__ // "user"
obj.__id__ // "7d40ab5352b0471cae5bdefc2e032840"
Live demo: http://jsfiddle.net/AJaBS/
for (var prop in c.success) {
alert(c.success[prop].__id__); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
and if the key is the same as the __id__ value, you can simply do:
for (var prop in c.success) {
alert(prop); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
Although Šime Vidas's use of Object.keys is more elegant, you will need the above code to work in older browsers unless you use what is called a him (i.e., you add some extra code which lets you use new standards today--i.e., an implementation of Object.keys which does the same thing as I did above, unless a built-in version already exists, in which case the shim will give preference to the built-in version).
You can use a simple loop:
for (var id in c.success) {
var obj = c.success[id];
// do something
}
If you want to ensure that only the first property in the object will be handled, you can add a break; statement in the end.
i have a map application, and in the interface, there a combo box contains 5 indicators(HDI, Life Expectancy, ..,..,..). I checked the 'data' of each indicator using FireBug 1.9.2, and I found that, inside the 'data' of each indicator the name of the indicator is listed and inside it there is a list of dates something like (1960.....up to 2010) some of these dates contains data according to its corresponding indicator and some of these dates contains no data "".
What i want to do is, to check the dates of each indicator and if the date contains data or value, i want to store that date otherwise do nothing with the date.
please see the snap shots i post maybe it would give clearer perception about what i want to do.
also please see how i tried to achieve this goal, but unfortunately the result is not what i want:
function getYearsByIndicator(layername, indicator) {
var matchingLayers;
var vectorLayer;
var yearStore;
// get vector layer
matchingLayers = map.getLayersByName(layername);
if (matchingLayers.length == 1) {
vectorLayer = matchingLayers[0];
}
else {
console.log("getThematicStyleMap: Warning, the layer " + layername + " was not found!");
return;
}
for (var i=0;i < vectorLayer.features.length;i++) {
if (vectorLayer.features[i]['data'][indicator]) {
// extract keys here!
}
}
//build store containing the extracted keys
//return the store
return yearStore;
}
Since its an object, I guess you can access it by:
$data->{propertyname}
EDIT: I was confused, I guess you are using javascript instead of PHP (which is one of your tags). When you are using javascript, you can access the values like your accessing arrays, so variable["property"]["subproperty"] etc
EDIT2: You can check it using
if(data["HDI"][1980] != "")
{
//date is not empty
}
EDIT3: Iterate over the content by using:
for(var key in data["HDI"])
{
//Key is 1980 etc
if(data["HDI"][key] != "")
{
//Date is not empty
}
}
For one reason or other ( I'm not going to go into why here) I need to use javascript to get the values of 12 hidden input fields and set a variable for each value.
I am not sure what the best approach for this would be. I'd like to be able to get the values and if they are not created i.e. the input fields are not there then id like to generate an error.
Would using a try / catch be good for this or should I simply be using typeof to check the variables have been created?
would putting them in an array as well so i can loop through to check their existance be a good idea?
thanks
This is the easy way of doing it. try-catch is rather heavy. Also, where would you throw the error to? Instead of unwinding your flow on error, collect your errors into a well structured response. That way if your first one is missing, but the other X are not, then you still get some work done.
if ( typeof( something ) !== "undefined" ) { doStuff(); }
Otherwise, I'd need more information to help you with your question.
Here's simple function that will check to see that exactly 12 input elements are included on the page. Please provide more information if you need th check that individual input elements are present.
function SaveInputValues() {
var inps = document.getElementsByTagName('input');
if (inps.length !== 12) {
return alert("There must be exactly 12 input elements. You have included " + inps.length + ".");
}
var vals = [];
for (i = 0; i < inps.length; i++) vals.push(inps[i].value);
inps = null; // provides closure
}
if(document.getElementById("someID")){
// add the value since the input exists
}
else{
// skip or use default - and inform if need be
}
Example implementation:
http://jsfiddle.net/zVz6h/1/
Code:
function getValueArray(idArray){
var valArray = [];
for(var i=0;i<idArray.length;i++){
if(document.getElementById(idArray[i])){
valArray.push(document.getElementById(idArray[i]).value);
}
else{
valArray.push("not defined");
}
}
return valArray;
}
var txtIDs = ["txt1","txt2","txt3","txt4","txt5","txt6","txt7","txt8"];
alert(getValueArray(txtIDs));