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.
In Javascript you can do the following:
Object.keys(ahash)[0];
for (key in dict) is likely to execute significantly faster, O(1) rather than O(n). It's not silly at all.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"
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.
objects are quite complex things, that implement: a key value store; a separate numbered value store (array); prototyping. the key value store part is a "dictionary". * Enumerating keys (e.g. Object.keys(someRandomObject) returns the keys not an arbitrary order, not a random order and not some other specific ordering, but in the same order as they were added. * in Python, your answer would be correct, as there is no "first" key. (i would guess that the "ordering" of keys returned in python has something to do with the key hash)Try this:
for (var firstKey in ahash) break;
alert(firstKey); // 'one'
var keyword; let or const will not suffice.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);
let [first] = Object.keys(ahash)