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
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'm trying to find a key value pair value but i want to pass the key in as an argument but it isn't seeming to work.
function drawPieChart(){
var findData = function(variable){
return dailyLog.find({createdBy: Meteor.user().username}, {fields: {variable: 1}}).fetch()[0].variable;
};
var data = [
{
value: findData(adherence),
color: "#CBDDE7"
}...
I want variable to be passed in twice, once to sort and other to find the value but it is actually looking for the key value pair "variable" which obviously doesn't exist.
How do i make it be seen as the argument?
There are two aspects to this:
Creating the fields object with a property whose name is the value of variable rather than the literal name variable, and
Accessing the resulting field based on the value of the variable (rather than the literal name variable)
Dealing with #2 first because it's easier: In JavaScript, you can access a property on an object either using dot notation and a property name literal (obj.foo), or using brackets notation and a property name string* (obj["foo"]). In the latter case, the string can be the result of any expression, including a variable lookup. So if variable contains "foo", then obj[variable] will get or set the foo property on obj.
Back to #1: For now, you have to create the object you're going to pass as fields first and then assign the property value via brackets notation rather than in an object initializer:
var fields = {};
fields[variable] = 1;
If variable contains "foo", then fields[variable] = 1 sets the foo property on fields to 1.
So putting that all together:
var findData = function(variable){
var fields = {};
fields[variable] = 1;
return dailyLog.find({createdBy: Meteor.user().username}, {fields: fields}).fetch()[0][variable];
// Note ------------------------------------------------------------------------------^--------^
};
In the next version of JavaScript, ECMAScript6 (aka ES6), you'll be able to do #1 with a "computed property name" in the object initializer (and still retrieve it with brackets notation). Perhaps unsurprisingly, computed property names use...brackets!
// ES6 only!!
var findData = function(variable){
return dailyLog.find({createdBy: Meteor.user().username}, {fields: {[variable]: 1}}).fetch()[0].[variable];
// Note ------------------------------------------------------------^--------^ --- and ---------^--------^
};
* Side note: In ES6, brackets notation can be used with things called Symbols as well as strings. It's not relevant to your question, but I said "string" above, and soon that won't be true, so...
How can you use the value of a key-value pair as the key in a different key-value pair in javascript?
I'd like to do the following:
var gizmos = {gizmo1: "G1"};
var things = {gizmos.gizmo1: "T1"};
So that things essentially equals:
var things = {"G1": "T1"};
Like this:
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1] = "T1";
There's no way to do it as part of the object initializer (aka object "literal"), you have to do it after.
The reason it works is that in JavaScript, you can access (get or set) a property on an object in two ways: Either using dotted notation and a literal, e.g. foo.bar, or using bracketed notation and a string, e.g. foo["bar"]. In the latter case, the string doesn't have to be a string literal, it can be the result of any expression (including, in this case, a property lookup on another object).
Side Note: If you change gizmos.gizmo1 after you do the things[gizmos.gizmo1] = "T1"; line, it does not change the name of the property on things. There's no enduring link, because the value of gizmos.gizmo1 was used to determine the property name during the things[gizmos.gizmo1] = "T1"; line (just like it is in any other expression).
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1]="T1";
To get the value for a given key on an object use object["key"] or object.key
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.