Going through a object with a variable [duplicate] - javascript
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.
Related
JavaScript and Consts [duplicate]
This question already has answers here: How to use a variable for a key in a JavaScript object literal? (16 answers) Closed 4 months ago. const A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP[A]); console.log(LOOKUP[0]); Result: undefined undefined Second try: var A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP[A]); console.log(LOOKUP[0]); Result: undefined undefined How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?
The correct way is: const A = 0; const LOOKUP = {}; LOOKUP[A] = 'A'; console.log(LOOKUP[A]); console.log(LOOKUP[0]);
const LOOKUP = { A : "A"}; The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"]) If you want the key to be a computed value, then you need to use square brackets: const LOOKUP = { [A]: "A" }; That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])
Looks like you are searching for some enums (typescript): enum ETest { A = 1 }; console.log(ETest['A']); // 1 console.log(ETest[1]); // A
Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined. You should try it as console.log(LOOKUP["A"])
This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect. const A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string). console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
Using a dynamic variable for the key of an object literal [duplicate]
This question already has answers here: How to use a variable for a key in a JavaScript object literal? (16 answers) Closed 4 years ago. I have a series of variables that I would like to pass into an object and I need the left side key to be pulled from a dynamic variable. How would I go about doing this? Here's an example: var characteristic = 'color'; var value = 'green'; // Desired JSON output var object = { color: 'green' }
like so: var characteristic = 'color'; var value = 'green'; var object = { [characteristic]: value } console.log(object);
How can I customize my object's property names with specific variable values without hardcoding them? [duplicate]
This question already has answers here: How do I create a dynamic key to be added to a JavaScript object variable [duplicate] (2 answers) Closed 5 years ago. I am creating a URL Parser for a school project. I first parse the full query from the url into an array, since query members are separated by "&". var queryString = /\?(\&?\w+\=\w+)+/.exec(urlString))[0].split("&"); Each array member would look like: arr[i] = "field=value"; I am doing this in an Object constructor in which I need to return an "HTTPObject". For the assignment, the HTTPObject must have a property called "query", and query should have many properties (one for each query field in the url). Why doesn't this work? queryString.forEach(function(element) { var elementArr = element.split("="); this.query.elementArr[0] = elementArr[1]; });
you cannt set a property like that - but you can with bracket notation: try this queryString.forEach(function(element) { var elementArr = element.split("="); this.query[elementArr[0]] = elementArr[1]; });
You were very close. You can refer to object properties by name, using square brackets... var queryString = ["name1=value1", "name2=value2"]; var query = {}; queryString.forEach(function(element) { var elementArr = element.split("="); query[elementArr[0]] = elementArr[1]; }); var varName = "name1"; console.log("by variable : " + query[varName]); // can use a variable console.log("by string : " + query["name1"]); // can use a string console.log("by propname : " + query.name1); // can hardcode the property name console.log("query object:"); console.log(query);
Jquery object assign to variable return undefined [duplicate]
This question already has answers here: Convert a JavaScript string in dot notation into an object reference (34 answers) Closed 7 years ago. Working SO code below: var property_object_parse = jQuery.parseJSON('{"p1":{"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_company name","text":"Company name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.15","y":"0.3","x":"0.53","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"company name","caption":"Company name","textType":"Company name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"left","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_first name","text":"First name","font":"Plantagenet Cherokee","size":"7","h":"0.1","w":"1.14","y":"0.44","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"first name","caption":"First name","textType":"First name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_last name","text":"Last Name","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.16","y":"0.56","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"last name","caption":"Last Name","textType":"Last Name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"2","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_email","text":"Email","font":"Plantagenet Cherokee","size":"6","h":"0.1","w":"1.14","y":"0.69","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"email","caption":"Email","textType":"Email","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"3","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_phone","text":"Phone","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.14","y":"0.81","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"phone","caption":"Phone","textType":"Phone","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"4","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_street","text":"street","font":"Plantagenet Cherokee","size":"9","h":"0.17","w":"1.16","y":"0.95","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"street","caption":"street","textType":"street","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"5","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]},"p2":{"ImageElement":[{"type":"image","text":"Sample.png","blockName":"Back Logo","id":"#2_Back Logo","lock":"false","rotation":"0","h":"0.68","w":"0.69","y":"0.59","x":"0.41","valign":"bottom","halign":"left","clippath":false}],"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Company Name","text":"Company Name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.16","y":"1.3","x":"0.24","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Company Name","caption":"Company Name","textType":"Company Name","bold":"false","colorspace":"DevicaeRGB","colorcode":"rgb(1.00,0.00,0.00)","color":"16711680","hex_color":"","valign":"bottom","align":"center","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Tagline","text":"Sample Tagline","font":"Helvetica","size":"12","h":"0.18","w":"0.73","y":"1.52","x":"0.25","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Tagline","caption":"Sample Tagline","textType":"Sample Tagline","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"top","align":"left","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]}}'); var selected_element = 'p1.TextElement[0].size'; console.log(property_object_parse.selected_element); I am getting undefined when I try to get the value using variable. Is this correct way to access it? See my jsfiddle here
property_object_parse is a real JavaScript object, so you can just use the member access syntax to access the value you are interested in directly: console.log(property_object_parse.p1.TextElement[0].size); Note that you cannot use a dynamic property path string like 'p1.TextElement[0].size', you would have to compile that in a way. For example, you could instead have an array of properties you are trying to access: var selected_element = ['p1', 'TextElement', '0', 'size']; var obj = property_object_parse; for (var i = 0; i < selected_element.length; i++) { obj = obj[selected_element[i]]; } console.log(obj); That has the same result as accessing it all directly as above with property_object_parse.p1.TextElement[0].size.
Variable variables in JavaScript? [duplicate]
This question already has answers here: "Variable" variables in JavaScript (9 answers) Closed 7 months ago. In PHP I can mess around with variable variables and I'm wondering if I can do the same in JavaScript. I want to create a new object with a property which's name is based on the value of a variable. if ( obj.name === 'foo' ) { var data = { foo: value }; } if ( obj.name === 'bar' ) { var data = { bar: value }; } Is there a shorter way of doing this without using eval()? Something like: var data = { obj.name: value };
Try this: var data = {}; data[obj.name] = value; You can read some more about js objects Here.
Objects in JavaScript are simply hash maps. You can access members by indexing with their names. For your problem you can use var data = {}; data[obj.name] = value; I've used this to implement a dynamic dispatch mechanism for arithmetic operations on different numerical types as described here.