[javascript] Get the first key name of a JavaScript object

Let's assume we have the following JavaScript object:

ahash = {"one": [1,2,3], "two": [4,5,6]}

Is there a function that returns the first key name for the given object?

From the example above I want to get one as a result of that function.

This question is related to javascript

The answer is


You can query the content of an object, per its array position.
For instance:

 let obj = {plainKey: 'plain value'};

 let firstKey = Object.keys(obj)[0]; // "plainKey"
 let firstValue = Object.values(obj)[0]; // "plain value"

 /* or */

 let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]

 console.log(key); // "plainKey"
 console.log(value); // "plain value"

I use Lodash for defensive coding reasons.

In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.

A "fully defensive" approach with Lodash would use both keys as well as get:

const firstKey = _.get(_.keys(ahash), 0);

There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:

for (var k in ahash) {
    break
}

// k is a key in ahash.

you can put your elements into an array and hash at the same time.

var value = [1,2,3];
ahash = {"one": value};
array.push(value);

array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.


Try this:

for (var firstKey in ahash) break;

alert(firstKey);  // 'one'

With Underscore.js, you could do

_.find( {"one": [1,2,3], "two": [4,5,6]} )

It will return [1,2,3]


If you decide to use Underscore.js you better do

_.values(ahash)[0]

to get value, or

_.keys(ahash)[0]

to get key.