Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of lists from list of json objects ruby

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.

like image 451
Bhawan Avatar asked Dec 17 '22 15:12

Bhawan


2 Answers

You were looking for following,

%i(a c).map { |x| test.map { |e| e[x] } }
like image 87
ray Avatar answered Feb 10 '23 00:02

ray


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]]
like image 24
3limin4t0r Avatar answered Feb 10 '23 01:02

3limin4t0r