Preface: Don't use for-in
to loop over arrays as in your example, at least not unless you're sure of what you're doing. More about looping arrays in this answer.
I was wondering if there are other ways to capture the object key if I know that there will be only one.
There's no shorter version of getting the only own enumerable property name from an object than Object.keys(obj)[0]
. But you can do it earlier if the [0]
is bothering you:
for(var i in arrOfObjs){ // See note above, don't use for-in here
var keyArr = Object.keys(arrOfObjs[i])[0];
// Note ------------------------------^^^
console.log(keyArr, arrOfObjs[i][keyArr]);
}
You could do this:
for(var i in arrOfObjs){ // See note above, don't use for-in here
for (var key in arrOfObjs[i]) {
console.log(key, arrOfObjs[i][key]);
break; // You've said you know there's only one, but...
}
}
...but it doesn't buy you anything other than (I suppose) avoiding calling Object.keys
, and in fact your Object.keys
code filters out inherited properties, which may be useful (though it's not necessary in your example).
The objects in your example don't have any inherited properties (unless someone's done something insane with Object.prototype
), but to be fully equal to your Object.keys
example, we'd have to throw in another function call:
for(var i in arrOfObjs){ // See note above, don't use for-in here
for (var key in arrOfObjs[i]) {
if (arrOfObj[i].hasOwnProperty(key)) {
console.log(key, arrOfObjs[i][key]);
break; // You've said you know there's only one, but...
}
}
}
And in fact, to be completely the same, we'd have to go further:
for(var i in arrOfObjs){ // See note above, don't use for-in here
for (var key in arrOfObjs[i]) {
if (Object.prototype.hasOwnProperty.call(arrOfObj[i], key)) {
console.log(key, arrOfObjs[i][key]);
break; // You've said you know there's only one, but...
}
}
}