jQuery expression as object key [duplicate] - javascript

This question already has answers here:
How to create an object property from a variable value in JavaScript? [duplicate]
(9 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to figure out how to create a dynamic key string for an object. This expression makes JavaScript complain.
return {$(this).val(): true}; // returns an object e.g. {2: true}
What am I doing wrong?

You have to create the object, then use bracket notation for the dynamic key
var obj = {};
var val = $(this).val();
obj[val] = true;
return obj;
or a completely unnecessary one-liner
return (function(o,e) {o[e.value]=true; return o;})({}, this);

The JavaScript object literal syntax {x: y} specifies that x will be a (possibly) quoteless string, and y any value. You can't use this syntax for dynamic keys.
Use this instead:
var foo = {};
foo[$(this).val()] = true;
return foo;

Related

Defining an object with a dynamic key in node js (javascript) [duplicate]

This question already has answers here:
How To Set A JS object property name from a variable
(8 answers)
Closed 4 years ago.
I need to do this :
let obj = {}
obj.obj1 = {'obj11':5}
console.log(obj.obj1.obj11)
//5
but I need to define the last key of the last object dynamically for example, something like this:
let obj = {}
key = 'obj11'
obj.obj1 = { key :5}
console.log(obj.obj1.obj11)
// undefined
Try
obj.obj1[key] = 5;
console.log(obj.obj1.obj11);
The object notation syntax does not support variables as keys directly, but java-script dictionaries do.
To evaluate the variable in the object notation syntax, use a bracket like so
obj.obj1 = {[key]: 5};
console.log(obj.obj1.obj11);
To define computed properties in javascript objects use [].
Try the following:
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
For reference : Reference
You'll have to use bracket notation for this like
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
Yes, you can do this:
console.log(obj.obj1[key]);
Every object in JavaScript is basically a dictionary so you can access it via the dictionary syntax.

In Javascript, how to convert a string to a property name? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
I have a global object with various properties whose values are strings. When a user types a string into an HTML input, I'm using javascript to assign that string to a variable. I need to convert that string to a property name and return the string associated with that property.
For example:
myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = document.getElementById('input').value;
myproperty = convertstringToProperty(str); //This is where I need a solution
return myglobalobject.myproperty;
}
Just use a computed property:
return myglobalobject[mystring];
This is a generalization of the fact that property accesses using dot notation are the same as accessing with brackets and a string literal:
obj.prop === obj["prop"];
So when you have something that isn't a string literal, just use the bracket notation.
Well, properties can be accessed with, you guess it, a string:
const myObject = {
property1: 0,
property2: 1,
};
const inputFromUser = 'property1';
console.log(myObject[inputFromUser]);
You don't even need a function:
var myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = 'anotherKey';
return myglobalobject[mystring] = undefined;
}
GetInput()
console.log(myglobalobject)

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.

Javascript - retrieve object property path [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
I have the following object
var obj = {};
obj.foo = {};
obj.foo.bar = "I want this";
given the "path" "foo.bar" as a string, how do I retrieve obj.foo.bar (or obj[foo][bar])?
Here's a way:
function getKey(key, obj) {
return key.split('.').reduce(function(a,b){
return a && a[b];
}, obj);
}
getKey('foo.bar', obj); //=> "I want this"
if path = "foo.bar" then you may write
var keys = path.split('.');
console.log(obj[keys[0]][keys[1]]);
just use the obj.foo.bar..that will work;

Javascript variable object keys [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
I am attempting to add a variable key, with no luck.
Here's what I got so far:
mysql('translations',{
check: 'element_id',
element_id: element_id,
{'lang-'+lang_id}: value
});
The variable key is the last line of the function.
Any ideas?
You can't use expressions for the identifiers in an object literal.
First create the object, then you can use dynamic names:
var obj = {
check: 'element_id',
element_id: element_id,
}
obj['lang-'+lang_id] = value;
mysql('translations', obj);
You can do this:
var x = {
check: 'element_id',
element_id: element_id
};
x['lang-'+lang_id] = value;
mysql('translations', x);

Categories