我有以下格式的 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 数组。
先谢谢您的帮助。
假设你有你的数组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"
# }
# ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句