Skip to content
Advertisement

Accessing Value in Array Object with Generic Variable for Key

I recognize that I can access the value of an object within an array by passing in the key name, like so:

   const batchNumValue = batchNumber[0]['MAX(batch_number) + 1'];

In my case I know the array will always contain exactly one object, with a single key/value pair, like so:

[{ 'MAX(batch_number) + 1' : 234 }]

That being the case, my question is, is there a way I can pass in a variable representing whatever that key name happens to be? Or does one have to always explicitly pass the key name, even in a situation like this?

Advertisement

Answer

You could get the values from the object and take the first item.

const
    data = [{ 'MAX(batch_number) + 1' : 234 }],
    value = Object.values(data[0])[0];

console.log(value);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement