Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  85] [ 1]  / answers: 1 / hits: 24473  / 9 Years ago, fri, february 13, 2015, 12:00:00

Here's my array (from Chrome console):



array



Here's the pertinent part of code:



console.log(hours);
var data = JSON.stringify(hours);
console.log(data);


In Chrome's console I get [] from the last line. I should get {'Mon':{...}...}



Here is the minimal amount of JavaScript to reproduce the issue:



var test = [];
test[11h30] = 15h00
test[18h30] = 21h30
console.log(test);
console.log(JSON.stringify(test)); // outputs []


I tried some other stuff like
Convert array to JSON or Convert javascript object or array to json for ajax data but the problem remains.


More From » arrays

 Answers
15

Here is the minimal amount of javascript to reproduce the issue



var test = [];
test[11h30] = 15h00
test[18h30] = 21h30
console.log(test);
console.log(JSON.stringify(test)); // outputs []


The issue with the above is that, while javascript will be happy to let you late-bind new properties onto Array, JSON.stringify() will only attempt to serialize the actual elements in the array.



A minimal change to make the object an actual object, and JSON.stringify works as expected:



var test = {}; // here is thre only change. new array ([]) becomes new object ({})
test[11h30] = 15h00
test[18h30] = 21h30
console.log(test);
console.log(JSON.stringify(test)); // outputs {11h30:15h00,18h30:21h30}

[#67835] Wednesday, February 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;