如何获取JSON数组中对象的索引?

杰克·麦康尼

我有以下格式的 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何从对象学生数组的索引中获取元素

如何从REstAssured中的Json数组中获取JSON对象

如何获取JSON对象中的数组数

在jq中获取对象数组索引

如何从JSON对象中的数组获取键名及其值

如何从对象数组中获取特定的JSON元素(jQuery)

如何从数组[JavaScript]获取对象的索引?

如何从角度或JavaScript的对象数组中获取比较值的索引

如何从python中的JSON对象获取数据数组?

如何从未命名的JSON对象数组中获取数据

存储过程:如何从多数组中的JSON对象获取数据

如何在JSON数组中的对象内获取JSON对象

如何使用angular获取数组中对象的索引?

如何从包含对象数组的json中获取特定对象

javascript json如何获取json数组中的键的索引

如何获取对象内部数组元素的索引?

如何获取数组中的对象索引

如何获取此数组中对象的索引?

如何从数组中快速获取对象索引

如何在REST API中从Json数组获取JSON对象

在JavaScript上的JSON对象中获取数组的索引

如何从数组中的JSON对象获取属性值并写入url

如何从json对象获取匹配元素的索引?

如何使用 jQuery 从 JSON 对象中的数组中获取值?

如何从js数组中获取json对象

如何获取数组中命名对象的索引

如何编写选择查询以从 Json 对象中获取索引值

获取数组中对象的所有索引 - 从对象中的数组

从与 JSON 对象数组匹配的巨大 JSON 对象数组中获取索引的最佳方法是什么