I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object
Related
vm.contributorAmountPerYear[index-1] gets me an object, and I want its key to be the year argument of the function.
function getAgriAmount(year,amount,index) {
if (typeof amount !== "number" ) {
amount = parseInt(amount ||0);
};
var argiYearlyLocalCost = vm.argiterraYearlyLocalCost;
console.log(vm.contributorAmountPerYear[index-1].year);
}
vm.contributorAmountPerYear[index-1][year]
For any javascript object, you should keep in mind that if you use . dot notation, you cannot access the properties for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case. This should work:
vm.contributorAmountPerYear[index-1][year];
Dot notation should be used when you already know the key:
var cuteJavaScriptObject = {
animal : 'cat'
}
var myVar = 'animal';
console.log(cuteJavaScriptObject.animal); // OK
console.log(cuteJavaScriptObject.myVar); // Wrong !!
console.log(cuteJavaScriptObject[myVar]); // Now OK
I have an object and I want to use object property value as key (simplified):
var App = function() {
this.settings = {
'tetris': {
title: 'Tetris'
},
'galaxian': {
title: 'Galaxian'
}
};
this.gameName = 'tetris';
this.request = {
this.settings[this.gameName].title: 'THIS KEY IS INVALID' // :(
}
};
I know I could assign it as:
this.request[ this.settings[this.gameName].title ] = 'Valid...';
But I wonder if I can define the property name using the object property value?
I am afraid, what you mean is not possible. You can not use a variable as a key in an object literal like this:
var key = "somekey";
var obj = {key: "value"}
The above code will result in an object that has the key key.
You can only use a variable to define an object element like this:
var key = "somekey";
var obj = {};
obj[key] = "value"
Then the object get's an element with the key somekey
EDIT: As stated in the comments, in ECMAScript 6 the support for computed properties in object literals got introduced. However the browser support for the computed properties in object literals is very slim (you can look it up here under syntax -> object literals). For example IE 11 has no support for it, neither has Chrome 43.
Computed property names will be introduced in ECMAScript edition 6, they're in the current draft, so you can do:
this.request = {
[this.settings[this.gameName].title]
}
They're reasonably well supported now, see MDN for more detail.
You can't define literal objects with computed property names; you have to assign them.
In other words, you can either define a literal object using {...} notation if the property name is well-known, or assign values into keys in a map using x[prop] = v notation if the property name is computed.
Think of your JS objects as being either objects or maps, but not both. If the JS object has well-known property names then it's acting as an object:
var obj = {
wellKnownPropertyName = 'value';
};
var value = obj.wellKnownPropertyName;
But if the property name is computed then it's not really a property of an object but more like a key in a map, and should be assigned (and read) as such:
var map = {};
var key = getUnknownKeyFromSomewhere();
map[key] = 'value';
var value = map[key];
Does anyone know what is test[name] mean?
function test(value){
copy(value||{},this);
}
test[name] = function(){
return "test"
}
This will be easiest to explain with an example:
var name = "foo";
test[name] = function(){
return "test"
};
This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.
You could call this function using any of the following methods:
test[name]()
test["foo"]()
test.foo()
Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.
Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.
test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.
This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.
All functions in Javascript are also objects. This adds a property to the test function object with a value which is an anonymous function.
For example:
function test(){
return "foo";
}
// test is a function, so it is also an object and
// it can have properties assigned to it
test.x = function(){
return "bar";
};
test(); // "foo"
test.x(); // "bar"
Of course just like with any object you can also use bracket notation:
var name = 'hello';
test[name] = function(){
return "HELLO!";
};
test.hello(); // "HELLO!"
In JavaScript, functions are objects. They have properties. test[name] sets a property (named whatever the name variable holds) to a function.
when you have a javascript object with defined properties you can access the property either with the dot notation obj.property or with the square brackets notation obj[property]
the property could also be a function so if you have an object:
var test = {
foo : function(arg){ console.log(arg) },
bar : 'hello'
};
you can call test.foo('bar') also by doing test['foo']('bar')
This is especially useful in iterations or when you dont know a priori what the name of the property is going to be. For example:
var fun = 'foo';
test[fun]('hello world');
Naturally it's up to you to do proper checks such as
if ('function'==typeof test['foo']){ test['foo']('bar'); }
Also note that you can do checks on the fly like so:
test[ fun || 'foo']('hello');
Taken from the Mozilla page
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of object members
There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).
So
test[name] = function (
means: there are (if everything is ok) two objects: test and name (and we know that at least test is present, because you defined it one line before: function test(value))
take the test object (if there isn't a test object an error will happen). Then access the key/value pair with the key calculated from the name object and there put a function.
Now, how the key is calculated from the name object? The same page from before tells us:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
Note that the description is a little wrong... test[null] == test["null"] and test[undefined] == test["undefined"], so perhaps the truth is that under the covers something like String(key).valueOf() is done (the String function will convert null to "null" and undefined to "undefined")
Some examples (where => means "is equivalent to, with this values")
var name = 'foo';
test[name] => test['foo']
var name = 123;
test[name] => test['123']
var name = 123.3;
test[name] => test['123.3']
var name = new Date();
test[name] => test['Wed Aug 14 2013 17:35:35 GMT+0200 (...)']
var name = null;
test[name] => test['null']
var name = undefined;
test[name] => test['undefined']
var name = [];
test[name] => test['']
var name = [1,2,3];
test[name] => test['1,2,3']
var name = {};
test[name] => test['object Object']
and so on...
The brackets are how you reference a property via a key into the hash that javascript objects are.
I would like to access the object provided only it's string path in form of array is known.
1.) there is an object, where
root["obj1"]["obj2"] = 1;
(in common case root["obj1"]...["objN"])
2.) I have ONLY string objectPath known:
var objectPath = 'root["obj1"]["obj2"]'
3.) I need NOT only READ the object, but SET it's value, like
objectPath = 2;
//so root["obj1"]["obj2"] === 2
As I understand
there might be some options with eval(), but it gets the value, not the variable;
one can loop through all objects of root, make convertion to "root.obj1.obj2" (which is not the case, as "obj1" can easily be "obj with spaces1") and check if given string equals to current object in the loop.
http://jsfiddle.net/ACsPn/
Related Link:
Access object child properties using a dot notation string
I wrote a function for you, trying to make it as pretty and reusable as possible :
function setProp(path, newValue, holder) {
var t = path.split(/[\[\]"]+/).filter(function(v){return v}),
l = t.pop(), s, o = holder || window;
while (s = t.shift()) o = o[s];
o[l] = newValue;
}
You use it like this :
setProp('root["obj1"]["obj2"]', 2);
If your root object isn't in a global variable, pass the relevant holder as third argument.
Demonstration (open the console to see the changed root object)
It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});