0
// Create the hashmap
var animal = {};
// Add keys to the hashmap
animal[‘cat’] = { sound: ‘meow’, age:8 };
animal[‘dog’] = { sound: ‘bark’, age:10 };
animal[‘bird’] = { sound: ‘tweet’, age:2 };
animal[‘cow’] = { sound: ‘moo’, age:5 };

I'm using the code above to try and create a hashmap. My question is, where sound and age are placed, how would I place them in using a variable.

For example

var one = 'sound';
var two = 'age';
animal['cat'] = {one: 'meow', two: 9};
  • Also: Use the correct quotes, `"` or `'`, not `‘`. (You could also use a template literal, but no need in the above.) – T.J. Crowder Jan 20 '17 at 08:47

2 Answers2

0

In ES2015+ it's

var one = 'sound';
var two = 'age';
animal['cat'] = {[one]: 'meow', [two]: 9};

Run it through a transpiler e.g. babel and you get

var _animal$cat;

var one = 'sound';
var two = 'age';
animal['cat'] = (_animal$cat = {}, _animal$cat[one] = 'meow', _animal$cat[two] = 9, _animal$cat);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

var animal = {};
var one = 'sound';
var two = 'age';

animal['cat'] = {};
animal['cat'][one] = 'meow';
animal['cat'][two] = 9;

console.log(animal);
Giladd
  • 1,351
  • 8
  • 9