How to get the value of key a and 'a' in javascript - javascript

How to get the value of key a and 'a' in javascript?
var obj = {a:1,'a':2}

The first key a will be overwritten by the second 'a'.
obj.a will return 2.
If your key name is a valid Javascript identifier or a number, Javascript will allow you to omit the quotes in key names. In practice, however, it's probably better to train yourself to always use quotes, to avoid confusion like this, and also because JSON requires them.

You can't - they are same key, and that initialiser will create an object with a single element 'a' with value '2'. Try this:
var obj = {a:1,'a':2};
for ( var i in obj )
{
alert(i + '=' + obj[i] );
}
And you'll just get "a=2' in response.

obviously, 'a' is the one-character string with a lowercase a as content; but what do you expect to be the other key? if you want it to be the value of a variable called a, then the curly braces syntax won't help you. Unlike Python, this syntax assumes the keys are strings, and quotes are optional.
You'd have to do something like this:
var a = 'givenkey'
var obj = {}
obj[a] = 1
obj['a'] = 2
this would create an object equivalent to:
var obj = {'givenkey':1, 'a':2}

If you not sure about key - use iteration
for(var k in obj)
alert(k + "=" + obj[k])
When you know key exact value use obj[k]

There isn't any difference.
alert([
obj.a,
obj['a']
].join("\n")); // returns 2 in both cases

Related

Create javascript object with string type key

I want to create an object some thing like this
var key = "key";
var obj={};
obj[key] = "value";
My required output is
{ "key":"valie"}
Key type must be string because i have keys like #12:5 , #12:89 ( orientDB ids ).
REASON:-
Because embeddedList of orientDB is not accepting any key without quotes.
Thanks
You're probably looking for JSON syntax.
Here's output from my console.
var key = "key"; //var not Var
var obj={}; //same here
obj[key] = "value";
"value"
obj
Object {key: "value"} //key is not in quotes, need to stringify!
JSON.stringify(obj);
"{"key":"value"}"
Object literals in javascript can be declared with quoted keys:
{
"Okeli-dokeli": "Flanders",
"Doh!": "Simpson!"
}
You can also dynamically assign values to a key in javascript with the bracket syntax:
var x = {};
x["A B C"] = "foo";
ADDED:
The JSON format is based on a subset of javascript but has object keys which are always quoted. Therefore converting any javascript object to JSON will "stringify" the keys:
> JSON.stringify( { a : 'b' } )
> "{"a":"b"}"
In the off chance you are not expecting nested objects, this can easily work as well:
var key = "key";
var obj={};
obj[key] = "value";
var s = "{\r\n";
for (var p in obj) s+= ' "'+p+'": "' + obj[p] + '"\r\n';
s += "}\r\n";
Also, it's var, not Var (no capital first letter).

Coffeescript one liner for creating hashmap with variable key

Is it possible to do the following in one line in coffeescript?
obj = {}
obj[key] = value
I tried:
obj = { "#{key}": value }
but it does not work.
It was removed from the language
Sorry for being tardy -- if I remember correctly, it was because some
of our other language features depend on having the key known at
compile time. For example, method overrides and super calls in
executable class bodies. We want to know the name of the key so that a
proper super call can be constructed.
Also, it makes it so that you have to closure-wrap objects when used
as expressions (the common case) whenever you have a dynamic key.
Finally, there's already a good syntax for dynamic keys in JavaScript
which is explicit about what you're doing: obj[key] = value.
There's something nice about having the {key: value, key: value} form
be restricted to "pure" identifiers as keys.
(obj = {})[key] = value
will compile to
var obj;
(obj = {})[key] = value;
This is normal javascript. The only benefit you get from coffeescript is that you don't have to pre-declare var s because it does it for you.
For anyone that finds this question in the future, as of CoffeeScript 1.9.1 interpolated object literal keys are once again supported!
The syntax looks like this:
myObject =
a: 1
"#{ 1 + 2 }": 3
See https://github.com/jashkenas/coffeescript/commit/76c076db555c9ac7c325c3b285cd74644a9bf0d2
Depending on how complex your key is you can always use a variable name matching your key and use it to define an object, like this:
myKey = "Some Value"
obj = {myKey}
Which will compile to:
var myKey, obj;
myKey = "Some Value";
obj = {
myKey: myKey
};
So what you end up with is something close to what you seek, but that requires your keys to be valid variable names.
If you're using underscore, you can use the _.object function, which is the inverse of the _.pairs function.
_.pairs({a: 1, b: 'hello'})
//=> [['a', 1], ['b', 'hello']]
_.object([['a', 1], ['b', 'hello']])
//=> {a: 1, b: 'hello'}
So, assuming myKey = 'superkey' and myValue = 100 you could use:
var obj = _.object([[myKey, myValue]]);
//=> obj = {superkey: 100}

Javascript distinguish a function in an object

Having an object like this:
var a = {
b: "string",
c: function(){
return "i return a string";
}
}
Doing
for (var key in a) {
console.log(typeof key);
};
Returns "string", "string" since b is a string and c returns a string.
Is there afunction that returns c -> function?
Returns "string", "string" since b is a string and c returns a string.
No. The reason it returns string, is that the attribute name b and the attribute name c are both strings; you're iterating over the keys of the object, not their values right now.
You could introduce attribute d, which was a function which returned a number or boolean, and you'd still get string.
Instead, enumerate over the values themselves;
for (var x in a) {
console.log(typeof a[x] );
};
If you want to see the type of the property instead of its key, should use the value together with the typeof operator.
for (var key in a) {
console.log(typeof a[key] );
};
Basically you will always get strings by iterating trough the keys of your object since they are represented as such.
But if you for example do console.log(typeof a[key]); Then you will get the expected output.
Change to:
for (var key in a) {
console.log(typeof a[key]);
};​
Live DEMO
console.log(typeof key); // gives you the key - "c"
console.log(typeof a[key]); // gives you the value of the "c" key - function.
Let me explain this little bit, so it's easy to understand to anyone. (its my first post here anyway.)
Try the following code, it says its a function.
console.log(typeof(a.c))
But what you have written is reading the property names. Try the following code to understand what's wrong with your code.
for (var key in a) {
console.log(key);
};
So basically what you are getting is correct. Because all property names are string.
Remember JSON objects have several restrictions, such as case sensitive, full path needed to traverse to properties etc..
Change your code as follows to get the typeof your properties,
Solution 1:
console.log(typeof(a[key]));
Solution 2:
console.log(typeof(eval('a.'+ key)));

How to use String representation of object property, operator, and value?

I'm trying to use a string value of say, "[ScheduledDate] < '11/1/2011'", and test for a bool value on an object like "item". But I can't seem to be able to figure out a way to do it successfully. I'm not wanting to use the eval function, but if it's the only way, then I guess I will have to. below is an example of the function I'm trying to use.
function _filterItem2() {
var item = { ScheduledDate: '1/1/2012' };
var filterExpression = "[ScheduledDate] < '11/1/2011'";
var result = item[filterExpression]; // This is where I'm not sure.
return result;
}
No, item[filterExpression] would just return the property named like your string.
Instead, you should store your filter expression as an object:
var filter = {
propname: "ScheduledDate",
operator: "<",
value: "1/1/2012"
};
Then get your comparison values:
var val1 = item[filter.propname],
val2 = filter.value;
and now comes the tricky part. You are right, you should not use eval. But there is no possibility to get the corresponding functions from operator names, so you will need to code them yourself. You might use a switch statement or a map like this:
var operators = {
"<": function(a,b){return a<b;},
">": function(a,b){return a>b;},
...
};
var bool = operators[filter.operator](val1, val2);

object Key in javascript class/dictionary?

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

Categories