1

I'm trying to test a set of some given variables. To organize the set, I'm adding the variables as keys to an object.

I think I'm on the right track with dynamically adding the key in accordance to the variable name. How can I ensure that each key's value corresponds to the value of the original given number?

example:

var num1 = 43;
var num2 = 597;
var num3 = 5662682;

I'd like for my object to basically come out like this:

{num1: 43, num2: 597, num3: 5662682}

I've tried:

function makeObj () {
  var obj = {};
  for (var i = 1; i <= 3; i++) {
    obj["num" + i] = "num" + i;
  }
  return obj;
}

but obviously, does not reference the variable. it stores a useless string.

{ num1: 'num1', num2: 'num2', num3: 'num3' }

how would I get the value of the said variable (num1, num2, num3) to be the value of the key of the same name, inside of my object?

I should also add, I'm looking to do this with standard Javascript and/or prototyping. No libraries or anything like that.

Rafael
  • 158
  • 2
  • 12

1 Answers1

0

you can use eval.

http://jsfiddle.net/afrievalt/w7fm3/

var num1 = 43;
var num2 = 597;
var num3 = 5663683;

function makeObj () {
  var obj = {};
  for (var i = 1; i <= 3; i++) {
    obj["num" + i] = eval("num" + i);
  }
  return obj;
}

Please don't tell Mr. Crockford I used eval. http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

@sabof and I like to use an array:

var nums = [];
nums.push(43);
nums.push(597);
nums.push(5663683);

function makeObj () {
  var obj = {};
  for (var i = 0; i <= nums.length; i++) {
    obj["num" + (i+1)] = nums[i];
  }
  return obj;
}
Mke Spa Guy
  • 793
  • 4
  • 13
  • Thank you for this and the link to the blog post. I've known about eval, but am unfamiliar with its upsides and downsides right now, so I'll check that out. – Rafael Mar 23 '14 at 22:43
  • 1
    About using an array, I didn't like it at first because the numbers were given to me as instantiated variables, but I see how it can be useful now as the use of the for-loop leaves us room to grow/shrink the array. Not that I had to use a for-loop if I stayed with objects.... And to use my given variables, all I'd have do is: nums.push(num1); nums.push(num2); nums.push(num3); – Rafael Mar 23 '14 at 22:50