In json can we get attribute value by passing variably value . Means
It works for me when "name" attribute exists in my "returnData" json object
// It works
var getColValue= returnedData[0].name
but it give undefined error
// It Not works
var refVar ="name";
var getColValue= returnedData[0].refVar;
var getColValue= returnedData[refVar];
should work. Please give it a try.
Use square bracket notation:
returnedData[refVar];
In other words, these two are basically equivalent:
returnedData["name"] === returnedData.name
Note that, using square-bracket notation allows you to set/get property names that wouldn't be valid with the dot notation. Eg, returnedData.some-prop is not a valid Javascript object, but returnedData["some-prop"] is.
Related
I am passing an object to a function. Simplified example below:
countyInfo(sales.NY2008);
The object is:
{countyName:"Albany",percentage:0.864789889,percentageComparison:40.18903649,sales:1222},
{countyName:"Allegany",percentage:0.789529462,percentageComparison:27.98874729,sales:149},
{countyName:"Broome",percentage:1.009475302,percentageComparison:63.64364553,sales:880},
{countyName:"Cattaraugus",percentage:0.874885092,percentageComparison:41.82554597,sales:276},
{countyName:"Cayuga",percentage:0.801267677,percentageComparison:29.89160156,sales:268},
{countyName:"Chautauqua",percentage:0.830185925,percentageComparison:34.5794701,sales:455},
{countyName:"Chemung",percentage:0.744919757,percentageComparison:20.75717391,sales:272},
{countyName:"Chenango",percentage:1.191003494,percentageComparison:93.07074993,sales:242},
{countyName:"Clinton",percentage:0.767315265,percentageComparison:24.38765663,sales:265},
{countyName:"Columbia",percentage:0.83461736,percentageComparison:35.29783949,sales:260},
{countyName:"Cortland",percentage:1.144086442,percentageComparison:85.46513794,sales:234},
It works beautifully.
Now I would like to compose this parameter from variables.
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales.getParameter)
It doesn't work as I'm passing a string. But how can this be done?
Just change your code to use bracket notation to access object property instead of dot notation
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales[getParameter]);
Dot notation:
Property identifies can only be alphanumeric (and _ and $)
Propertyidentifiers cannot start with a number.
Property identifiers cannot contain variables.
OK — obj.prop_1, obj.prop$
Not OK — obj.1prop, obj.prop name
Bracket notation:
Property identifiers have to be a String or a variable that
references a String.
It is okay to use variables, spaces, and Strings
that start with numbers
OK — obj["1prop"], obj["prop name"]
For Detailed explanation refer this --
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Since sales seems to be an object, you can use index notation to access a member.
That is, sales.NY2008 is equivalent to sales["NY2008"].
So, simply do
countyInfo(sales[getLocation + getYear]);
I've retrieved a JSON response from an external API and one of the variable names begins with a # character, so the JSON variable looks like this #text. Unfortunately angular doesn't know how to handle this variable, is there any way delete the # so that the data assigned to the identifier is usable.
In order to reference a property that does not follow the rules for a properly formatted identifier, you must use bracket notation instead of dot notation for the property accessor:
var object = JSON.parse('{"#text":"https://lastfm-im...png","size":"extralarge"}')
console.log(object['#text'])
you cam modifide the response - loop throw it wite map- and chenge the object key -see here:
JavaScript: Object Rename Key
You can use square bracket notation instead of dot notation. like (Object mutation is highly not recommended)
//to access it u can use square bracket notation like k["objectname"]
let k = {"#test":"some data"}
alert("data is "+k["#test"])
I have an array and object in js:
var number = [23,234,654,3234];
var detail = {
23:"John",
234:"Doe",
654:50,
3234:"blue"
};
Then using var remove = number.shift(), I can get the first value in the array (in this case, 23) and remove it from the array.
I am trying to remove the corresponding property from the object: In this case, it will be 23:"John".
I tried delete detail.remove; but no luck.
Any suggestions?
Thanks
According to MDN the delete operator is followed by an expression that should evaluate to a property reference. Your example delete detail.remove is in fact correct.
However, if you want to access a property programmatically (or numbered property, such as 23), use bracket notation.
// with variable
delete detail[remove];
// with string or integer
delete detail[23];
you can't use variable in obj.variable, the right way is obj[variable].
So try this instead:
delete detail[remove];
I get the following json array from an api:
response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
I get that from the following http query:
$http.get(url).success(function(response){
let assume that
quote = "AUD";
How can I point to the AUD value of rates in response (i.e. rate = 1.3997)?
$scope.rate = response.rates.quote;
does not work...
this is called accessing property value of an object this is how we do it
var quote = 'AUD'
var response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
object = JSON.parse(JSON.stringify(response))
document.write(object.rates[quote])
If you use
rates.quote
This means that quote is a property of rates object which is not;
The value of quote is the property of rates
Try like this
$scope.rate = response.rates[quote];
This is one of those times when you have to use the square bracket notation instead of dot notation even though they are usually interchangeable. You can only use dot notation when you know the real name of the property. When you are using a variable as a placeholder you have to use square brackets.
Dot notaion has its limit, use brackets as others already suggested.
The dot notation is:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.
proyectos.each(function(index){
var proyNombre = this.value;
if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
}
else{
console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
console.log(myArray.this.value); //doesnt work either
}
});
Try:
console.log(myArray[proyNombre]);
myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:
var myObject = {};
myObject.test = 'test string';
var s = 'test';
console.log(myObject.s); // wrong!!
but you could then do:
console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
You need to use the same syntax you used to set the value:
console.log(myArray[proyNombre]);
Simply access the value with myArray[proyNombre].
You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.
If you change:
console.log(myArray.proyNombre);
console.log(myArray.this.value);
to
console.log(myArray[proyNombre]);
console.log(myArray[this.value]);
You should get the same value (the value for the key represented by the variable proyNombre) logged twice.
It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.