【问题标题】:How to send a Ruby hash object with objects as keys to front end Javascript as a Map object如何将带有对象作为键的 Ruby 哈希对象作为 Map 对象发送到前端 Javascript
【发布时间】:2021-10-12 05:29:59
【问题描述】:

Javascript 不支持将对象作为对象键,但 Map 对象支持。我的问题是,有没有办法轻松地将这样的对象从后端发送到前端?

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)
  }
})

正如预期的那样,在前端记录的response,因为它被转换为JSON,在后端内置了object作为字符串键。

// console response
response = {{"a"=>"1","b"=>"2"}: 5}
// further inspection
Object.keys(response)[0] = "{\"a\"=>\"1\", \"b\"=>\"2\"}"

有什么方法可以在前端轻松地将它转换为 Map 对象以再次将对象作为键,或者在渲染过程中表明这一点?

我目前的解决方案只是 JSON.parse,但这似乎很笨重

JSON.parse(Object.keys(response)[0])

【问题讨论】:

标签: javascript ruby-on-rails json


【解决方案1】:

您正确地注意到,在 JS 中,对象键应该是字符串。那么为什么不简单地使用字符串呢?

# In Ruby
def test_controller
  object = {"a"=>1,"b"=>2}
  front_end_object = {"key"=>object, "value"=>5}   # Look here
  render json: front_end_object, status: 200
end

// In JS
$.ajax({
  type:"POST",
  url: "/pull_from_test_controller",
  dataType:"json",
  contentType:"application/json",
  data: {},
  success: function(response, status_string, jqxhr) {
     console.log(response)
     // Should be: {"key":{"a":1,"b":2},"value":5}

     // Then no need to parse or anything, just access the values directly.

     console.log(response.key)     // {"a":1,"b":2}
     console.log(response.key.a)   // 1
     console.log(response.key.b)   // 2
     console.log(response.value)   // 5
     
  }
})

我建议你使用一些比keyvalue 更有意义的名称;)

【讨论】:

    猜你喜欢
    • 2011-03-29
    • 2017-04-04
    • 1970-01-01
    • 2011-06-29
    • 2013-02-09
    • 2022-01-05
    • 1970-01-01
    • 2015-05-13
    • 2011-03-12
    相关资源
    最近更新 更多