Get the value of an object with an unknown single key in JS

Osama picture Osama · Aug 25, 2015 · Viewed 13.8k times · Source

How can I get the value of an object with an unknown single key?

Example:

var obj = {dbm: -45}

I want to get the -45 value without knowing its key.

I know that I can loop over the object keys (which is always one).

for (var key in objects) {
    var value = objects[key];
}

But I would like to know if there is a cleaner solution for this?

Answer

Blauharley picture Blauharley · Aug 25, 2015

Object.keys might be a solution:

Object.keys({ dbm: -45}); // ["dbm"]

The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.

As James Brierley commented below you can assign an unknown property of an object in this fashion:

var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;

But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.