【问题标题】:select in a parsed json, comparing id with an array of ids在解析的 json 中选择,将 id 与 id 数组进行比较
【发布时间】:2017-02-25 12:17:55
【问题描述】:

我需要过滤数组结果(通过解析的 json 获取)。

如果我知道我可以使用 json 在 json 中选择的确切 ID

@my_art = ele_art.select { |articolo| articolo['id'] == 456 }

现在我有一个名为 @myarray 的 id 数组,我需要在 ele_art 中仅选择数组中具有 id 的项目

读取我拥有的数组:

[279, 276]

我试过了

@my_art = ele_art.select { |articolo| articolo['id'] == @myarray }

@my_art = ele_art.select { |articolo| articolo['id'] in @myarray }

没有运气!

我该如何解决?

【问题讨论】:

  • 我明白了,所以,在 @myarray 你有 [279, 276] ?,在这种情况下,试试:@my_art = ele_art.select { |articolo| @myarray.include?(articolo['id']) }。让我知道这是否有帮助。
  • 太棒了!这解决了我的问题!如果您在 answare 中转换评论,我可以标记解决方案! ;-)

标签: ruby-on-rails arrays json


【解决方案1】:

@my_arrayids 的数组,因此,在这种情况下,您需要检查articolo['id'] 是否包含在@myarray 中。对于这些情况,Ruby 中的 Array 类具有 include? 方法,该方法接收 object 并在对象是否包含在数组中时返回 true/false。

所以,在你的情况下尝试类似:

@my_art = ele_art.select { |articolo| @myarray.include?(articolo['id']) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多