Verty00 Verty00 - 2 months ago 11
Ruby Question

How do I pull out an object from an array that contains a key with a certain value

My question is how to I pull out a specific object from this array that has an 'id' with the specific value of 888?

[{ "token" => "1212",
"category" => "A",
"name" => "page 2",
"id" => "888"
},

{ "token" => "3434",
"category" => "B",
"name" => "page 1",
"id" => "999",
}]


I have tried find_by, where, and a whole host of other things.

Answer

You can try using "select" on the array:

arr.select {|k| k['id'] == "888" }

This will return an array containing all array elements where the condition is met.