2

I have this:

var a = {};
a[1] = 1;
a[4] = 4;
console.log(JSON.stringify(a));

then I get:

{"1":1,"4":4}

but I want to get:

{1:1,4:4}

how to reach this? In other words, I want to keys be real int.

John Smith
  • 6,129
  • 12
  • 68
  • 123

3 Answers3

3

When you call JSON.stringify() method it creates a valid JSON string. One of the rules for valid JSON is that every property should be in "quotes".

So thats why it is impossible to get such result as you want using JSON.stringify.

If you want to just convert such object to array it is possible, for example usin such function.

function numerableObjectToArr(obj) {
  var result = [];
  var keys = Object.keys(obj);
  keys.forEach(function(item){
    result.push(obj[item]);
  })
  return result; 
}

var a = {};
a[1] = 1;
a[4] = 4;
numerableObjectToArr(a); // returns [1, 4]

But in this way you will just receive Array with values of existing properties in the obj.

But if your prop name means the index in the array, and you are sure that there will be always number as a prop name - you can improve this function:

function numerableObjectToArr(obj) {
  var result = [];
  var keys = Object.keys(obj);
  keys.forEach(function(item){
    result[+item] = obj[item];  //we put index, then we put value to that place in array
  })
  return result; 
}

var a = {};
a[1] = 1;
a[4] = 4;
numerableObjectToArr(a);  // returns [undefined, 1, undefined, undefined, 4]
Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • yea, I see, I realized that its a server-side issue: http://stackoverflow.com/questions/3445953/how-can-i-force-php-to-use-strings-for-array-keys – John Smith Jun 28 '16 at 08:01
1

I'm not sure you can do what you're trying to do the as the keys have to be string values. I'd advise having string name for your keys (i.e 1 = One, 2 = Two, etc). You could then try this:

 var a = {};
    a.one = 1;
    a.two = 2;
    a.three = 3;
    a.four = 4;

    console.log(JSON.stringify(a));

I hope this helps.

k..a..b
  • 61
  • 1
  • 12
-1

var a = {};
a[1] = 1;
a[4] = 4;
alert(JSON.stringify(a).replace(/\"([0-9]+)\":/g, '$1:'));

But it is kludge. JSON - has a string keys.

Alexander Goncharov
  • 1,572
  • 17
  • 20