简体   繁体   中英

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

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM