Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 804
Osama Avatar asked Aug 25 '15 16:08

Osama


People also ask

How do you find the value of an object without a key?

How to get all property values of a JavaScript Object (without knowing the keys) ? Method 1: Using Object. values() Method: The Object. values() method is used to return an array of the object's own enumerable property values.

How do I get one key from an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.

How can I get object value in JavaScript?

values() The Object. values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)


2 Answers

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.

like image 57
Blauharley Avatar answered Nov 08 '22 22:11

Blauharley


There's a new option now: Object.values. So if you know the object will have just one property:

const array = Object.values(obj)[0];

Live Example:

const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);

If you need to know the name of the property as well, there's Object.entries and destructuring:

const [name, array] = Object.entries(obj)[0];

Live Example:

const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);
like image 44
T.J. Crowder Avatar answered Nov 08 '22 21:11

T.J. Crowder