I apologize there are similar threads but I can't solve this issue. I have a JSON object that contains keys and values (representing file IDs and file names). Since a JS object cannot be sorted, I need to convert to an array, sort by value (i.e., file name) NOT by key (i.e., file ID). I can accomplish all this except when converting to array, I am losing my keys/file IDs (e.g., 110, 111, 112) and they are replaced with the default array keys (0,1,2, etc.).
// Assign object to a var
$obj_win_top_get_files = window.top.<?php echo $_GET['files']; ?>;
Looking at the object via console.log,
console.log('checked_boxes', $obj_win_top_get_files);
I see:
Object {110: "013_904_general.docx", 111: "013_902_info.docx", 112: "013_120_list.docx"}
// Sort JSON object by file name ("value") rather than by id ("key")
// Create an array first since JS object is NOT sortable
arr_ids_filenames = new Array();
// Loop thru JS object to populate new array so it can be subsequently sorted
$.each($obj_win_top_get_files, function (key, value) {
console.log(key, value);
// Populate array
arr_ids_filenames[key] = value;
});
// Sort array by values
arr_ids_filenames.sort();
// THIS IS WHERE I AM LOSING THE FILE IDs (keys)
$.each(arr_ids_filenames, function (key, value) {
// Array may contain keys/IDs with no values/file names so make sure there is a value
if(value){
console.log(key, value);
$the_ul.append('<li id="chk_file_' + key + '">' + value + '</li>');
}
});
Everything works except they keys are not the file IDs (110,111,112), they are the default array keys (0,1,2). It is something in the $.each() that I am not doing correctly. I am close, but have not been able to solve this one. Any recommendations will be greatly appreciated.
$_GET['files']without any sanity checks is a REALLY bad idea. XSS, CSRF etcArray.sort