0
var arr=[];
arr['first']='val1';
arr['second']='val2';


var json=JSON.stringify(arr);
var obj=JSON.parse(json);  //obj is array

Can I return object {"first":"val1","second":"val2"} ?

P.S.: I read Convert Array to Object topic

I'm interested in this way of the function

Community
  • 1
  • 1
Michael Phelps
  • 3,451
  • 7
  • 36
  • 64

2 Answers2

2

If somebody has abused arrays like that, JSON does not help you. It will only serialize the numeric indices of Array objects, nothing else. Copy the properties by hand:

var obj = {};
for (var prop in arr)
    if (arr.hasOwnProperty(prop)) // don't copy enumerables from Array.prototype
        obj[prop] = arr[prop];

console.log(obj); // {"first":"val1","second":"val2"}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You shouldn't use an array to represent this:

Do this instead:

var obj = {first:"val1",second:"val2"};

Just define the object directly . Stringify and parsing is not necessary

TGH
  • 38,769
  • 12
  • 102
  • 135