Create list of lists from list of json objects ruby

Viewed 845

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.

2 Answers

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]]
Related