user1243746
user1243746

Reputation:

Get key of a hashmap withou know it's name

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

Answers (2)

ZER0
ZER0

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

Andreas Wong
Andreas Wong

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

Related Questions