2

I have the following array of objects

position = [
    {exchange: 'KRAKEN', USD: 1800, EUR: 800, GBP: 800, BTC: 800},
    {exchange: 'BTCE', USD: 800, EUR: 800, GBP: 800, BTC: 800},
    {exchange: 'BITSTAMP', USD: 600, EUR: 800, GBP: 800, BTC: 800},
    {exchange: 'MYWALLET', USD: 1300, EUR: 800, GBP: 800, BTC: 800}
]

I also have 2 variables: myExchange and myCurr

I'm attempting to extract the relevant currency value from the array. i.e. if myExchange = 'KRAKEN' and myCurr = USD,then I need to fetch the result as = 1800

I'm using the following code in coffeescript (and underscore ._ as library) but it is returning as 'undefined'

    objBuy = _.find(position, (objBuy) ->
      objBuy.exchange is buyExchange
    )

    objBuyCurr = _.find(objBuy, (objBuyCurr) ->
      objBuy._key is buyCurr
    )

Eventually what I'm aiming for is to pass the object property/keys as variables dynamically. i.e.: value = position.myExchange.myCurr (and NOT position.KRAKEN.USD)

0

1 Answer 1

1

You might want to form your data not using an array, but with a hash table (an object in JavaScript terms) which uses exchange values as keys:

position = {
    'KRAKEN': { USD: 1800, EUR: 800, GBP: 800, BTC: 800},
    'BTCE': { USD: 800, EUR: 800, GBP: 800, BTC: 800},
    'BITSTAMP': { USD: 600, EUR: 800, GBP: 800, BTC: 800},
    'MYWALLET': { USD: 1300, EUR: 800, GBP: 800, BTC: 800}
};

And then extract the required field with:

position['KRAKEN'].USD

or

position.KRAKEN.USD

In you have the name of field in a variable, for example:

var myExchange = "KRAKEN";
var myCurr = "USD";

then remember that you can access any field of an object as if it was an index of an array:

position[myExchange][myCurr];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Suseika. What I need however is to be able to say: position.myExchange.myCurr. i.e. us the variables dynamically. Is that possible at all ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.