Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

People also ask

Can JS object have duplicate key?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


In Javascript you can do the following:

Object.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 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"

If you decide to use Underscore.js you better do

_.values(ahash)[0]

to get value, or

_.keys(ahash)[0]

to get key.


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]