Amit
Amit

Reputation: 1919

how to access immediate unknown key in object

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

pic

Upvotes: 13

Views: 13133

Answers (3)

Laz
Laz

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

Here's the fiddle

Upvotes: 0

Michael Radionov
Michael Radionov

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;

http://jsfiddle.net/mGZpa/

Upvotes: 19

Jashwant
Jashwant

Reputation: 28995

You can iterate through the object.

var quotes = {
    '367:sl': 'cptyname'
}

for(var i in quotes) {
    alert(quotes[i]);
}

Demo

Upvotes: 2

Related Questions