Used function argument to access JSON Array javascript - javascript

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.

Related

I want to display data out of JSON

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

Using dot notation with number passed into function

If I have an object and function
var obj {
"1234": {"example": "sample"},
"5678": {"example": "sample"}
}
function example(num, str) {
if obj[num].hasOwnProperty(str) {
//manipulate property
}
return obj;
}
then later call the function,
obj(1234, "example")
Why do I have to write obj[num] instead of obj.num? Shouldn't dot notation be acceptable because the value being passed will always be an integer and not have quotations around it, i.e. obj.1234 would work but not obj."string"?
Why do I have to write obj[num] instead of obj.num?
Because obj[num] takes the value of num (for instance, 1234) and uses that value as the property name, but obj.num uses "num" (literally) as the property name. Brackets vs. dot is how the JavaScript parser knows when you're giving the property name literally (dot notation) or using an expression you want to use the result of (brackets notation).
(Side note: Granted, when we do foo[1], we literally mean the property 1 in foo. But from the parser's perspective, we're effectively using an expression there.)

Passing a parameter into a Javascript method

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.

Why is this json example an object is parsed as an array [duplicate]

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

How to access attribute of object as a variable?

I have two objects:
object1={
type: 'obj1',
nName: 'nName'
}
object2={
type: 'obj2',
pName: 'pName'
}
In my js code, I have:
object=GET_OBJECT();
The GET_OBJECT() method returns either object1 or object2, then, I would like to access the object's name attribute which is either nName or pName.
I have one method which will get the name (pName or nName) of the returned object:
function getName(Object, name){
return object.name;
}
where I would like the name to be a variable, so that I can access the pName or nName in this way:
object=GET_OBJECT();
var name='';
if(object.type=='obj1')
name='nName';
else
name='pName';
var finalName=getName(object, name);
But seems it won't work since in:
function getName(Object, name){
return object.name;
}
name is a variable. In JS, is there any way to access attribute as a variable?
Try like this:
function getName(Object, name) {
return Object[name];
}
AS many times before I wonder why people provide solutions and not knowledge. Otherwise the asker will repeat the same mistakes over and over.
The original code uses a function to retrieve an attribute. It is assumed that it is possible to use the parameter to invoke the parameter. In more technical words, Dot notation is being used which must be a valid JavaScript identifier. Tha name after the dot is the pointer the content. Therefore getName always is accessing the attribute name which is likely to be undefined.
The solution shown uses Bracket notation in which uses the content of the parameter (which may not exist) as identifier and then, it resolves the content and this is why it actually works.
Dot notation is faster and easier to read and would be adviced if both are valid options. Bracket notation is to be used when you need resolving in run time. That is what happens when you define setters and getters internally. The following code will use the string passed to ensure (using bracket notation) that whenever you use the identifier by dot notation will call the functions passed.
function myClass(){
//setX and getX should be also defined previous to this
this.__defineSetter__("x",this.setX);
this.__defineGetter__("x",this.getX);
//Object.defineProperty can also be used
};
var tObject = new myClass();
tObject.x = 10; //Getter being called

Categories

Resources