0
votes

Received json encode object from server side in php MONTHLY_FORMAT, read that object in jquery as

var MONTHLY_FORMAT = '<?php echo $MONTHLY_FORMAT; ?>';

Here in console get output like this:

{"01":"January","02":"February","03":"March","04":"April","05":"May","06":"June","07":"July ","08":"August","09":"September","10":"October","11":"November","12":"December"}

but after doing JSON parse

var MONTHLY_FORMAT_PARSE = JSON.parse( MONTHLY_FORMAT );

return output like

{10: "October", 11: "November", 12: "December", 01: "January", 02: "February", 03: "March", 04: "April", 05: "May", …}

How would I get the month json object list in proper month sequence ?

2
The problem is the "number" is actually interpreted as a string... I try to parse it in PHP and get the same result as well... You can force to parse the key in PHP as an int.Eiji

2 Answers

0
votes

try:

const ordered = {};
Object.keys(MONTHLY_FORMAT_PARSE).sort().forEach(function(key) {
    ordered[key] = MONTHLY_FORMAT_PARSE[key];
});

(NOTE: The proper month sequence will now be in the variable "ordered ")

0
votes

I know this is an old question, but since it's not properly answered, i want to just clarify to anyone else that ever come across this doubt:

Objects have key sorting naturally in specific contexts, since it's not wise to trust it, if you want to maintain your data sorted in a specific sequence use an Array instead.

Here some snippet with two possible solutions (one still using objects, but not really indicated, and the other with an array of months):

// If you want to stick with the object key sorting, even it being not really trustable, simply remove the '0' in the beginning of each numeric key in your JSON string (if this don't causes any kind of trouble in your context)
let obj1 = JSON.parse(`{"01":"January","02":"February","03":"March","04":"April","05":"May","06":"June","07":"July ","08":"August","09":"September","10":"October","11":"November","12":"December"}`.replace(/"0/g,'"'));

console.log(obj1);
/* Output:

{
  "1": "January",
  "2": "February",
  "3": "March",
  "4": "April",
  "5": "May",
  "6": "June",
  "7": "July ",
  "8": "August",
  "9": "September",
  "10": "October",
  "11": "November",
  "12": "December"
}

*/

// Using array to mantain the desired element sort, using the received object as it comes from your PHP server
let obj2 = JSON.parse(`{"01":"January","02":"February","03":"March","04":"April","05":"May","06":"June","07":"July ","08":"August","09":"September","10":"October","11":"November","12":"December"}`);

let monthList = Array(12).fill(0).map( (m, i) => obj2[`${i+1}`.padStart(2,'0')]);

console.log(monthList);

/* Output:
[
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July ",
  "August",
  "September",
  "October",
  "November",
  "December"
]
*/