0

I have an array with data from an API.

Here is the data from the API.

[
  {
    "id": "litecoin",
    "name": "Litecoin",
    "symbol": "LTC",
    "rank": "6",
    "price_usd": "48.5624",
    "price_btc": "0.0128526",
    "24h_volume_usd": "198794000.0",
    "market_cap_usd": "2576800216.0",
    "available_supply": "53061632.0",
    "total_supply": "53061632.0",
    "percent_change_1h": "-1.98",
    "percent_change_24h": "6.07",
    "percent_change_7d": "-0.51",
    "last_updated": "1506172141",
    "price_eur": "40.637987568",
    "24h_volume_eur": "166354795.08",
    "market_cap_eur": "2156317957.0"
  }
]

I am trying to get price_eur. I know I can do this with

data.price_eur

The thing is eur can change to any other currency. So if I want to get USD is use

data.price_usd

But the currency will be variable. So I want to make the text after 'price_' variable.

I have tried something and have no succes yet. Here is what I have tried.

inputCrypto = 'eur';        
var priceCURCrypto = 'price_' + inputCrypto;
var priceCUR = data[0].priceCURCrypto;

Can someone tell how to use a variable when looking through an array.

user234562
  • 631
  • 9
  • 20
  • Instead of answering the same thing for the zillionth time, the answerers here should just vote to close this as a duplicate, which is clearly the case. – Gerardo Furtado Sep 23 '17 at 13:30

3 Answers3

2

With dot notation you can't do this, since what comes after the dot is considered a literal property name.

But you can with square-bracket notation, which takes the property name as a built string, which means you can concatenate with variables and expressions.

foo.bar; //looks for the property @bar
foo[bar] //looks for the property *whose name is stored* in the variable @bar

So in your case:

data[0][priceCURCrypto];

Here's more info on dot vs. square-bracket syntax.

Mitya
  • 33,629
  • 9
  • 60
  • 107
1

Use brackets

var priceCUR = data[0][priceCURCrypto];
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42
0

You can use [] notation to access the properties which name is in the variable. It will evaluate the expression inside the [] and use the result as the property name.

inputCrypto = 'eur';        
var priceCURCrypto = 'price_' + inputCrypto;
var priceCUR = data[0][priceCURCrypto];

Examples

const obj = { nameA: 'NameA', nameB: 'NameB' };
const name = 'name'
const propName = name + 'A';

// Value of the propName is 'nameA', get the property with name 'nameA'
console.log(obj[propName]);
// Use string concatenation
console.log(obj[name + 'B']);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112