How can I safely use variables in objects? [duplicate] - javascript
This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
in javascript is it possible to construct an object literal with expressions evaluating to strings for property names? [duplicate]
(2 answers)
variable in javascript statement
(2 answers)
Closed 8 years ago.
I'm bored and messing with my console and I came up with the following code:
I was trying something like:
x = 16;
y = 26;
f = { x+y:"String!"};
expecting something or somehow to do:
Object {1626: "String!"}
Or at least
Object {42: "String!"}
I ended up with
x = 16;
y = 26;
eval("f = { "+x+y+":\"String!\"}");
Which returned as expected:
Object {1626: "String!"}
I've always been told to avoid eval() and never even think about using it due to something about security. Is there a way to use variables in declaring the property (Sorry if I don't know what it's called exactly)
x = 16;
y = 26;
f = {};
f[x+''+y] = "String!"; // For f[1626]
or
f[x+y] = "String!" // For f[42]
I made this exact same mistake when I started learning JavaScript: JavaScript set object key by variable
You first must make the object:
var f = {};
Then you can use variables to dynamically create keys:
var x = 16, y = 26;
f[x+y] = "Integer";
f[x.toString() + y.toString()] = "String";
Related
Javascript Need a basic syntax explaination [duplicate]
This question already has answers here: JavaScript by reference vs. by value [duplicate] (4 answers) Closed 2 years ago. var x = 5; function test2(x) { x = 7; } test2(8); alert(x); Why exactly is this putting out the global var x=5, without being affected by anything within the function.
Because you passed a param called x, which is the same name as your global var. Try this out: var x = 5; function test2(y) { x = y; } test2(8); alert(x);
adding a variable while trying to access an object [duplicate]
This question already has answers here: Accessing an object property with a dynamically-computed name (19 answers) Closed 2 years ago. So below I have a variable newVal. Inside that variable are objects such as profileNum1 and inside that userEmail which I can access via let profile = newVal.profileNum1.userEmail; which would return a string such as 'users#email.com' let newVal = JSON.parse(value); for (let z = 0; z < 100; z++) { console.log('LOOP HAS BEGAN RUNNING' + z); let profile = newVal.profileNum1.userEmail; console.log('LOOK FOR MEEEEEEEEEEEEEE' + profile); Now I need to basically add the variable z into profileNum in replacement of 1. I tried achieving this via let profile = newVal.profileNum + z.userEmail; Which does not work it just returns NaN so I am assuming I am unable to do it that way since with z = 1 during the loop it should return a result when it hits z = 1 in the loop but it still returns NaN. I am pretty stumped on how I can add the variable Z into that and it still use it to select the object profileNum1, profileNum2, etc. Any help would be appreciated =]
Use bracket notation: let profile = newVal["profileNum" + z].userEmail; This will parse profileNum0, profileNum1, profileNum2 etc. and access it - basically doing this: let profile = newVal.profileNum0.userEmail; // When z is 0 let profile = newVal.profileNum1.userEmail; // When z is 1 let profile = newVal.profileNum2.userEmail; // When z is 2
Why is the y-array changing when I modify the x array? javascript [duplicate]
This question already has answers here: Why does changing an Array in JavaScript affect copies of the array? (12 answers) Closed 3 years ago. // x = [7,2] let x = [7, 2]; // y = [[7,2]] let y = [x] // x = [9,2] x[0] = 9; // y also = [[9,2]] console.log(y); Why is it that when I changed x, y changed as well? Shouldn't y still be what it was when I initialized it [[7,2]]? What is this phenomenon called?
In javascript when you copy over array to another variable, it does not copy over the data to another variable. It will create a reference to that variable, so when the original array changes, copied over array would also change this is called as call by reference. Another term is called as call by value which will copy over the data to another variable, which is the case for primitive data types
Copying value by reference. - https://www.dyn-web.com/javascript/arrays/value-vs-reference.php What you want to do instead - let x = [7,2]; let y = [...x]; x[0] = 9; (2) [9, 2] y (2) [7, 2]
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);
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.