Reputation: 1919
how to access immediate unknown key in object. in pic "367:sl" is dynamic key and i want to access cptyName value which is in "367:sl". Thanks in advance
Upvotes: 13
Views: 13133
Reputation: 143
Based on the answer of @Michael Radionov, a more slick definition of the firstKey
variable would be to replace:
var firstKey = Object.keys(quotes)[0];
with the more slick:
const [firstKey] = Object.keys(quotes);
using array destructuring
As correctly noted by @Unmitigated, it can be done even faster by using Object.values
directly.
Full code (updated for 2022):
//Objects
const quotes1 = {
"367:sl": { //unkown key
cptyName: "bank1"
}
};
const quotes2 = {
"999:sl": { //unknown key
cptyName: "bank2"
}
};
// Arrow function to get the (first) value of unknown Object key
getCptyName = quotes => Object.values(quotes)[0].cptyName;
console.log(getCptyName(quotes1)); //bank1
console.log(getCptyName(quotes2)); //bank2
Upvotes: 0
Reputation: 13309
If your dynamic key is the only key in quotes
object, you can get the first key and then access value with:
var firstKey = Object.keys(quotes)[0];
var cptyName = quotes[firstKey].cptyName;
Upvotes: 19