when I alert btnName it is not fetching the attr name and instead using the text btnName.
var btnName = orderBtn.attr("name");
var obj = {btnName:true,json:1};
I am sure this is possible, I just can;t figure it out.
You need to write it like this:
var obj = {json: 1}
obj[orderBtn.attr('name')] = true
There's no way to include an expression (such as a variable) as a key when constructing an object using literal notation.
var obj = {foo: 'bar'}
is essentially shorthand for
var obj = {'foo': 'bar'}
If you want to refer to a variable foo, you need square bracket notation:
var obj = {}
obj[foo] = 'bar'
var btnName = orderBtn.attr ("name");
var obj = { json: 1 };
obj [btnName] = true;
Use brackets if you want to use a variable as a key:
var obj = { json: 1 };
obj[btnName] = true;
Related
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;
In Typescript I would like the myObj variable to be:
{'key01': 'value01'}
So I go ahead with:
let keyName = 'key01';
let myObj = {keyName: 'value01'};
console.log(myObj);
But the resulting variable is
{ keyName: 'value01' }
Can I use the value of the keyName variable to use as the key name for the variable myObj?
If you don't want to waste space with an extra line of code for defining the main object and then defining the custom key, you can use bracket notation inline.
let keyName = 'key01';
let myObj = { [keyName]: 'value01' };
console.log(myObj);
You can use the bracket notation property accessor:
let keyName = 'key01';
let myObj = {};
myObj[keyName] = 'value01';
console.log(myObj);
For TypeScript, use:
let keyName = 'key01';
let myObj:any = {};
myObj[keyName] = 'value01';
If you want to change the value of your object using the variable keyName you can use the following.
let keyName = "newValue";
let myObject = {keyName: "oldValue"}
myObject.keyName = keyName
console.log(myObject)
Here is Code
var str = "Value1";
var str1 = "Value2";
var obj = {
[str]: str1
};
console.log(obj);
I am getting obj as
{
Value1:"Value2"
}
But I want this object as
{
"Value1":"Value 2"
}
Can any one explain how it is possible?
At first your code: var obj = {["Value1"]: "Value2"}; is wrong. You have to write:
var obj = {"Value1": "Value2"}; or var obj = {Value1: "Value2"};.
And then if I understood you correctly: in your comment you wrote:
I wana get Value1 in double quotes too dynamic means I want dynamic index too in double quotes
The answer:
Object {Value1:"Value2"} is the same like {"Value1":"Value2"}. The difference is to see in displaying (spelling, writing) of your code only.
For example you will not see the difference if you execute following code:
var myObj1 = {"Value1":"Value2"};
var myObj2 = {Value1:"Value2"};
console.log(myObj1.Value1); //Value2
console.log(myObj2.Value1); //Value2
console.log(myObj1["Value1"]); //Value2
console.log(myObj2["Value1"]); //Value2
console.log(JSON.stringify(myObj1)); //{"Value1":"Value2"}
console.log(JSON.stringify(myObj2)); //{"Value1":"Value2"}
The question is similar to this: How do I interpolate a variable as a key in a JavaScript object?
However, I have a difficult on using variables on nth keys:
I had a object, which is:
var object = {};
object.foo = "foo";
object.foo.bar = "bar";
object.foo.bar.alice = "alice";
object.foo.bar.alice.bob = "bob";
I am able to get the value (foo) for object.foo by using the variable object["foo"]
But I cannot find out a way to access to object.foo.bar value.
I tried object["foo"]["bar"], but it does not work.
In addition to my question, how can I get the value for
object.foo.bar.alice
object.foo.bar.alice.bob
By using variable as well?
Thanks.
You need an object for foo, because foo is a primitive type.
var object = {};
object.foo = "foo";
object.foo.bar = "bar"; // does not work!
This works
var object = {};
object.foo = {};
object.foo.bar = "bar"; // work!
When you do
var object = {};
object.foo = "foo";
You define the property as string and it won't store the keys since it is a string literal not a string object.
you need to try
var object = {};
object.foo = new String("foo");
Now it can store more properties in object.foo.
var object = {};
object.foo = new String( "foo" );
object.foo.bar = new String( "bar" );
object.foo.bar.alice = new String( "alice" );
object.foo.bar.alice.bob = new String( "bob" );
console.log( object );
you need to assign as a object {key:value,key:value}
object.foo = {0:"foo",bar:{}};
object.foo.bar = {0:"bar",alice:{}};
object.foo.bar.alice = {0:"alice",bob:{}};
object.foo.bar.alice.bob = "bob";
console.log(object.foo.bar.alice);
console.log(object.foo.bar.alice.bob);
You can develop a simple function to get the nested objects and their keys dynamically. Such as the following. A similar approach would be sufficient for the set version as well.
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var arr = [{fox: [{turn:[857, 432]}]}, {sax: [{pana:[777, 987]}]}, {ton: [{joni:[123, 567]}]}, {piu: [{burn:[666, 37]}]}, {sia: [{foxy:[404, 696]}]}],
myObj = {foo: {bar: {alice: {bob: "bob"}}}};
document.write("<pre>" + JSON.stringify(arr.getNestedValue(3,"piu",0,"burn",1),null,2) + "</pre>");
document.write("<pre>" + JSON.stringify(arr.getNestedValue(3,"piu",0,"burn"),null,2) + "</pre>");
document.write("<pre>" + JSON.stringify(myObj.getNestedValue("foo","bar","alice","bob"),null,2) + "</pre>");
Keep in mind that you can set your nested properties in an array in the order of appearance and then call like myDeeplyNestedObj.getNestedValue(...propsArray)
I couldn't add the variable value as my key name in backbone.js is there any way to do this ?? look at the code below
(function ($) {
Today = Backbone.Model.extend({
});
var data= ['a','b','c'];
for(var i=0;i<data.length;i++){
today.set({i:data[i]});
}
} (jQuery));
how i am able to do that ?
You should be able to simply pass data to today.set().
var data = ['a','b','c'];
var today = new Today();
today.set(data);
console.log(today.attributes);
// {0: "a", 1: "b", 2: "c"}
Though, to explain the problem: Identifiers on the left-hand of : in Object literals always become the key's name themselves. To use a variable's value as a key, you have to use bracket member operators.
var tmp = {};
tmp[i] = data[i];
today.set(tmp);
So in javascript an object literal with unquoted key uses the string version of that key:
var i=1;
var obj = {i: "this sets obj.i to this string, not obj['1']"};
If you want a computed key, follow this pattern:
var keyname = i + 'whatever' + 42;
var obj = {};
obj[keyname] = value;