If I had a JSON object formatted like this:
{
"CampaignID":5918,
"CampaignFolder":"http://www.Dan.com/campaign/5918-18D/",
"TargetUser.CampaignID":5918,
"TargetUser.GUID":"3dbe24a8-a3e3-4de9-86ab-4940c8e148cc",
}
Once I grab the object and I want to display an alert with a property, I can use alert(CampaignID) and it correctly displays 5918. But if I try alert(TargetUser.CampaignID) it fails. Any ideas?
The way the object is structured, you're going to need to use bracket notation to access those fields. The object key is "TargetUser.CampaignID" but the JS you're using: TargetUser.CampaignID means access the object TargetUser and access its property CampaignID when really you just want "TargetUser.CampaignID" as a string key.
Try something like this
var data = {
"CampaignID":5918,
"CampaignFolder":"http://www.Dan.com/campaign/5918-18D/",
"TargetUser.CampaignID":5918,
"TargetUser.GUID":"3dbe24a8-a3e3-4de9-86ab-4940c8e148cc",
};
alert(data["TargetUser.CampaignID"]);
alert(data["TargetUser.GUID"]);
// data["TargetUser.CampaignID"] is NOT data.TargetUser.CampaignID
// that would look like this: {TargetUser: {CampaignID: 0}}
// not {"TargetUser.CampaignID": 0}
:
There are two ways to access properties of object in js
Dot notation and
Bracket notation.
With Dot notation -
property must be a valid JavaScript identifier. For example,
object.$1 is valid, while object.1 is not.
With Bracket notation -
property_name is a string or Symbol. It does not have to be a
valid identifier; it can have any value, including 1foo, !bar!, or
even " " (a space) or a . (dot character)
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
Related
I have a basic function taking an argument. I will use this argument to as index to access the array in JSON file. I want to take advantage of this argument instead of hard-coded inside the function. However, for some reasons, javascript is not return me the right value.
var obj = {
"first":[
["aaaaa"],
["bbbbb"],
["ccccc"],
["ddddd"],
["eeeee"]
]
}
I have a javascript function to access the file.
function addElement(ID) {
console.log(obj.ID);
}
and now if I use
addElement("first"); //this return me undefined.
I do not want to explicitly mention obj.first in order to access the right JSON object. I would like to make it more generic so that the method can be re-used. Am I missing anything here?
Thanks...
JavaScript supports both dot notation and a property name literal (obj.foo), and brackets notation and a property name string (obj["foo"]).* In the latter case, the string can be the result of any expression.
So you'd need brackets notation, not dot notation:
function addElement(ID) {
console.log(obj[ID]);
}
obj.ID accesses the property ID. obj[ID] accesses the property whose name is the string from the variable ID.
* Just for completeness: In ES6, it will support property name Symbols in brackets notation as well, but that's not relevant to your code.
I have the following code:
function isFieldEmpty(input)
{
if(document.frmRegister.input.value == "")
{
return false;
}
return true;
}
I call it using isFieldEmpty("fieldName"). However, I think the "input" bit is incorrect...
Can anyone help?
That code is looking for a property literally called "input" on frmRegister. To look for "fieldName" for example (the value of input), you want bracketed notation:
if(document.frmRegister[input].value == "")
// Change -------------^-----^
In JavaScript, you can access the property of an object using either dot notation and a literal property name (obj.foo) or using bracketed notation and a string property name (obj["foo"]). In the latter case, the property name string can be the result of any expression, including a variable or argument lookup.
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I have this JSON code :
{
"query": {
"pages": {
"-1": {
"ns": 0,
"title": "StackOverflow",
}
}
}
}
I parsed it into a JSON object :
data = JSON.parse(jsonString);
Why to access the object -1 I must do data.query.pages[-1] not data.query.pages.-1. In this example pages is not an array but an object.
It's not an array, it's an object. Both object["name"] and object.name are identical ways of accessing a property called name on the given object.
You cannot access an object property with object.-1, simply because that's a syntax error, the same way you can't use object.+1 or object.[1 or object./1. They're all valid names for a property of an object, but they're syntactically invalid when using object.propertyName syntax.
The other caveat is that you cannot have property names which are integers. Setting or getting object[-1] is identical to object["-1"] as the property name is converted to a string. It would be identical to accessing object.-1 if that were valid syntax.
You can't do data.query.pages.-1 for the same reason you can't do var -1;: -1 is not a valid identifier.
But that's not a problem.
foo.bar // Access member bar of object foo
is just a shortcut for
foo["bar"] // Access member bar of object foo
so you can do
data.query.pages["-1"]
You could even do
data["query"]["pages"]["-1"]
Bracket notation has nothing to with arrays, it's just another way to access properties. In fact, the reason why we can only use bracket notation for arrays is because of the evaluation rules: To use dot notation, the property name must be a valid identifier name.
Or simply put:
You can only use dot notation if the property name would be a valid variable name or a reserved word.
And -1 doesn't fall in that category (you can't do var -1 = 'foo'; for example).
Examples for invalid identifier names:
0foo, -foo, &bar
anything that doesn't start with a letter, _ or $
foo-bar, foo+bar, foo bar
anything that contains something that is not a letter, a digit, _ or $ (or fall into specific unicode ranges, see the spec).
However, using reserved words is possible, even though they can't be used as variables:
foo.if // valid
var if = 42; // invalid
Maybe is just a stupid question, but,
I would appreciate having an explanation of the following behavior:
var obj = {
key : "val1",
123 : "val2"
};
obj.key; // "val1"
obj.123; // Syntax error: missing; before statement
obj[123]; // "val2"
Why obj.key is different from obj.123
although they have been declared both as keys of obj.
Accessing the object literal in this way obj.123 is wrong.
And declaring the object in the following way is correct?
The browsers I have tested are IE9, firefox and chrome and for all of them it works fine.
var obj = {
123 : "val1"
};
JavaScript will let you use just about any string as an object property name, but when accessing properties with the dot notation you're only supposed to use property names that would be valid JS identifiers - which have to start with a letter, the underscore or a dollar sign. So for property names that don't meet the rules for valid identifiers you have to access them with the bracket notation.
Although the bracket notation works with a number, behind the scenes JS will convert that number to a string.
I bumbed into one of those moments when I just lose the focus and start wondering on a silly question:
var a = {
b: "value"
}
What is the typeof 'b' and I don't mean the typeof "value", but the actual Key labeled as b?
background:
I started wondering about this when I had to create a key which is a string:
var a = {
"b": "value"
}
because at a later point it is referenced as:
a["b"]
And then ended up wondering about the original question.
In object literal terms, b is a property. Properties are either strings or symbols in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters.
for (key in a) {
alert(typeof key);
//-> "string"
}
Property names are automatically coerced into a string. You can try this yourself by using a numeric literal as a property name.
var object = {
.12e3: 'wut'
};
object[.12e3]; // 'wut'
object['.12e3']; // undefined
object['120']; // 'wut'
// Let’s try another numeric literal:
object = {
12e34: 'heh'
};
object[12e34]; // 'heh'
object['12e34']; // undefined
object[1.2e35]; // 'heh'
object['1.2e35']; // undefined
object[1.2e+35]; // 'heh'
object['1.2e+35']; // 'heh'
For this reason, I’d recommend using only string literals for property names.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
b is a string, it's just a shorthand syntax, so you write
var a = {
b: "value"
}
instead of
var a = {
"b": "value"
}
Keep in mind that JavaScript objects are hash tables and the keys are just strings. You may omit the quotes around property names during declaration, but if you use reserved words for property names or any other name that happens to be an invalid identifier, such as starting with a digit, or containing spaces, you would have to wrap the property names in quotes:
var a = {
"1b": "value",
"b and c": "value",
"+12345": "value"
};
Also note that you can reference the properties of objects using the dot notation or the subscript notation regardless of whether quotes were used when they were declared. However, if you use property names that would be invalid identifiers, such as the ones in the above example, you are forced to use the subscript notation:
a.1b // invalid (dot notation)
a["b and c"]; // valid (subscript notation)
var a = {$ : 'hello', 2123 : 'number'};
for(var key in a) {
console.log(typeof key)
}
Keys in javascript objects can be strings and symbols. symbol is a primitive data type in javascript.