John Smith John Smith - 4 months ago 10
Javascript Question

Convert javascript object keys to real int after JSON encoded

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.

Answer

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]
Comments