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"} ?
PS: I read Convert Array to Object topic
I'm interested in this way of the function
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"}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.