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)
Related
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.
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.
Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Use variable for property name in JavaScript literal?
Is it possible to add a variable as the property name of an object in JavaScript, like this:
var myVar = "name";
var myObject = {
{myVar}: "value"
};
Edit
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
var myVar = "name";
var myObject = {
[myVar]: "value"
};
You can use the [] syntax to use an expression as the property name (compared to the .prop and prop: value syntaxes where they are always treated as strings):
var myObject = {};
var myVar = "name";
myObject[myVar] = "value";
There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.
Like this?
var myVar = "name";
var myObject = {};
myObject[myVar] = "value";
Yes, but not directly.
var myVar = "name";
var object = {};
object[myVar] = "value";
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;
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
Is it at all possible to use variable names in object literal properties for object creation?
Example
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.propertyName); // Prints "value"
console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){
var myObject = { [propertyName] : "Value"};
}
Note browser support is currently negligible.
You can sort of do this:
var myObject = {};
CreateProp("myProperty","MyValue");
function CreateProp(propertyName, propertyValue)
{
myObject[propertyName] = propertyValue;
alert(myObject[propertyName]); // prints "MyValue"
};
I much perfer this syntax myself though:
function jsonObject()
{
};
var myNoteObject = new jsonObject();
function SaveJsonObject()
{
myNoteObject.Control = new jsonObject();
myNoteObject.Control.Field1= "Fred";
myNoteObject.Control.Field2= "Wilma";
myNoteObject.Control.Field3= "Flintstone";
myNoteObject.Control.Id= "1234";
myNoteObject.Other= new jsonObject();
myNoteObject.Other.One="myone";
};
Then you can use the following:
SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);
NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.
function func(prop, val) {
var jsonStr = '{"'+prop+'":'+val+'}';
return JSON.parse(jsonStr);
}
var testa = func("init", 1);
console.log(testa.init);//1
Just keep in mind, JSON property names need to be enclosed in double quotes.
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }