【问题标题】:How to get index of an object in JSON array?如何获取 JSON 数组中对象的索引?
【发布时间】:2017-10-23 03:20:15
【问题描述】:

我有以下格式的 JSON 数组,如何使用其键获取对象的位置(索引)?

json = [
    {
        "id"=>1, 
        "user_name"=>"Mean Dean", 
        "user_profile_id"=>"1", 
        "amount"=>4
    },
    {
        "id"=>2, 
        "user_name"=>"Mad Stan", 
        "user_profile_id"=>"2", 
        "amount"=>7
    },
    {
        "id"=>3, 
        "user_name"=>"Jack Dean", 
        "user_profile_id"=>"3", 
        "amount"=>8
    }
]

例如,如果我想获得第一个元素的位置,如果我得到它的 id(在本例中为 1),我将如何处理它。我阅读了 index 方法,但不知道如何将其应用于 JSON 数组。

提前感谢您的帮助。

【问题讨论】:

  • 您的问题标题与您实际提出的问题无关。请说明到目前为止您已经尝试过什么,以及导致错误的原因。
  • 没有从上一个问题更新对不起这个愚蠢的错误

标签: ruby-on-rails json ruby


【解决方案1】:

假设您的数组位于json 变量中,您可能会使用Enumerable#detect

json.detect { |e| e['id'] == 1 }
#⇒ {
#           "amount" => 4,
#               "id" => 1,
#        "user_name" => "Mean Dean",
#  "user_profile_id" => "1"
# }

要获取此元素的索引,可以使用Enumerable#find_index

json.find_index { |e| e['id'] == 1 }

要更新这个对象,你只需更新返回的哈希值:

json.detect { |e| e['id'] == 1 }['amount'] = 500
#⇒ 500
json
#⇒ [
#  [0] {
#             "amount" => 500,  ⇐ !!!!!!!
#                 "id" => 1,
#          "user_name" => "Mean Dean",
#    "user_profile_id" => "1"
#  },
#  [1] {
#             "amount" => 7,
#                 "id" => 2,
#          "user_name" => "Mad Stan",
#    "user_profile_id" => "2"
#  },
#  [2] {
#             "amount" => 8,
#                 "id" => 3,
#          "user_name" => "Jack Dean",
#    "user_profile_id" => "3"
#  }
# ]

【讨论】:

  • 我需要该位置,以便如果存在具有给定 id 的对象,我可以更新“数量”,这将返回该对象。我将如何操作它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2018-04-25
  • 2014-11-30
  • 1970-01-01
  • 2020-05-04
相关资源
最近更新 更多