Reputation:
Having one only key/value into an object, how to get them without know the key name? (If it's possible)
var m = {x:5}; // we don't know x is the key
Upvotes: 2
Views: 1905
Reputation: 25322
An alternative to for…in
loop, if the browser support ES5 (or has a shim for ES5):
var key = Object.keys(m)[0];
See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
Upvotes: 0
Reputation: 60526
You can use hasOwnProperty
for things like this
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty
var m = {x:5};
function keys(obj)
{
var keys = [];
for(var key in obj)
{
if(obj.hasOwnProperty(key)) {
{
keys.push(key);
}
}
return keys;
}
console.log(m);
So using this knowledge, you can write a function that basically checks whether a given key exists in an object:
function hasKey(obj, key) {
return obj.hasOwnProperty(key);
}
Upvotes: 1