I have a list of json objects something like this:
test = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c":6}]
I want to fetch the fields 'a'
and 'c'
from the above test list to create a list of list something like this:
[[1, 4], [3, 6]]
The idea is to make a list of all the values of a, then the values of c.
When I am using pluck:
test.pluck(:a, :c)
I am getting output like this:
[[1, 3], [4, 6]]
One approach I tried which is working fine.
res = []
res << test.pluck(:a)
res << test.pluck(:c)
But I am thinking it would be better if I get one or two liner solution,
with or without inbuilt function
because the number of fields in the future may increase.
You were looking for following,
%i(a c).map { |x| test.map { |e| e[x] } }
You could use Array#transpose
on the pluck
result. Which assumes the array represents rows or columns and swaps the representation around.
test.pluck(:a, :c).transpose
#=> [[1, 4], [3, 6]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With