-1

I need to generate a object with number object property using javascript new Object().

For example I want to create a object dynamically by the below format {1:"1",2:"2",3:"5"}

I tried below

var json_str=new Object();  
$([1,2,3]).each(function(i,t){
        var str="'json_str."+t+"="+t+"'";
        eval(str);
});

But it is not created object like that, if it is string value it will create.

Merbin Joe
  • 121
  • 1
  • 15
  • Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Sebastian Simon Nov 21 '17 at 18:36

3 Answers3

2

You could use Object.assign and map the objects.

var array = [1, 2, 3],
    object = Object.assign(...array.map(k => ({ [k]: k.toString() })));

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Values should be strings – mhodges Nov 21 '17 at 18:38
  • @JustinNiessner JavaScript keys are always strings. It's not possible to have an integer key – mhodges Nov 21 '17 at 18:42
  • @mhodges I know. Which is why the now-deleted answer that says this isn't possible was the one I up-voted first. But it technically was wrong since you can also use `Symbol`s as keys. – Justin Niessner Nov 21 '17 at 18:43
  • @JustinNiessner True, you can use Symbols as keys as well, although they don't show up in `Object.keys()` or `for...in`, so they work differently than traditional string properties. But meh, semantics. – mhodges Nov 21 '17 at 18:49
2

Simple JS:

let array = [1, 2, 3];
let object = {};

for (let num of array) {
  object[num] = String(num);
}

console.log(object);
console.log(Object.keys(object)); // your keys will automatically become strings too

You should avoid using eval() where-ever possible to prevent accidental injection exploits.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
0

I think you want to make this an Array, then you can push objects onto it:

var json_str=new Array();  
$([1,2,3]).each(function(i,t){
   json_str.push( { [t] : t });
});

json_str: Array(3)
0:{1: 1}
1:{2: 2}
2:{3: 3}
AC__
  • 51
  • 7