While Javascript does not natively support objects as object keys, the Map object offers a solution. My query is, how can an object like this be transmitted easily from the backend to the frontend?
def test_controller
object = {"a"=>1,"b"=>2}
front_end_object = {object => 5}
render json: front_end_object, status: 200
end
$.ajax({
type:"POST",
url: "/pull_from_test_controller",
dataType:"json",
contentType:"application/json",
data: {},
success: function(response, status_string, jqxhr) {
console.log(response)
}
})
Upon logging the response
in the frontend, the expected JSON conversion results in the backend's object
being represented as a string key.
// console response
response = {{"a"=>"1","b"=>"2"}: 5}
// further inspection
Object.keys(response)[0] = "{\"a\"=>\"1\", \"b\"=>\"2\"}"
Is there a straightforward method to convert this back to a Map object in the frontend, allowing the object to be used as a key once more, or any way to address this during rendering?
Currently, my approach is to use JSON.parse, although it feels somewhat cumbersome.
JSON.parse(Object.keys(response)[0])