writingdeveloper
writingdeveloper

Reputation: 1076

How to get javascript object's value with key

I have a object like this code

var coinNameKR = {
  BTC: 'bitcoin',
  ETH: 'ethereum',
  DASH: 'dash',
}

And I want to get each value's with the key. So I search on stackoverflow and find this code

function getValueByKey(object, row) {
  return Object.values(object).find(x => object[x] === row.key);
}

console.log(getValueByKey(coinNameKR, row.key));

But It seems it only returns bitcoin only.

For example if

console.log(getValueByKey(coinNameKR, 'ETH'));

it should be ethereum, but still bitcoin. And I found get Key By Value but I can't not find get value by key.

Upvotes: 2

Views: 14631

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21628

var coinNameKR = {
  BTC: 'bitcoin',
  ETH: 'ethereum',
  DASH: 'dash',
}

const dumpProps = obj => Object.keys(obj).forEach(key => { console.log(`${key}'s value is ${obj[key]}`) });

dumpProps(coinNameKR);

Upvotes: 1

Nam V. Do
Nam V. Do

Reputation: 705

Is that is what you are looking for?

var coinNameKR = {
  BTC: 'bitcoin',
  ETH: 'ethereum',
  DASH: 'dash',
}
for(let i in coinNameKR){
  console.log(`${i} has the value: ${coinNameKR[i]}`)
}

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

You just need to return the value of the key in the object:

var coinNameKR = {
  BTC: 'bitcoin',
  ETH: 'ethereum',
  DASH: 'dash',
}

function getValueByKey(object, row) {
  return object[row];
}

console.log(getValueByKey(coinNameKR, "ETH"));

Upvotes: 4

Related Questions