How to get certain attributes of an array of objects in JSON

时间:2017-06-15 09:38:02

标签: ruby-on-rails arrays json ruby

I have an array of JSON object.

arr =  [{'a'=> 1, 'b'=> 2, 'c'=> 3}, {'a'=> 4, 'b'=> 5,'c'=> 6}, {'a'=> 4, 'b'=> 5,'c'=> 6}]

But I want an new array which select 'a' and 'c' attributes only:

new_arr = [{'a'=> 1, 'c'=> 3}, {'a'=> 4,'c'=> 6}, {'a'=> 4,'c'=> 6}]

I try to use map but for 1 attribute only arr.map{|i| i['a']}. What I am missing or any suggestion?

3 个答案:

答案 0 :(得分:5)

Make use of slice and pass the attributes you want to select

arr =  [{'a'=> 1, 'b'=> 2, 'c'=> 3}, {'a'=> 4, 'b'=> 5,'c'=> 6}, {'a'=> 4, 'b'=> 5,'c'=> 6}]

arr.map{|a| a.slice('a', 'c')}
#=> [{"a"=>1, "c"=>3}, {"a"=>4, "c"=>6}, {"a"=>4, "c"=>6}]

答案 1 :(得分:3)

You can use except

new_arr = arr.map{ |e| e.except('b') }

答案 2 :(得分:3)

Since, there are already answers describing usage of slice and except, I would provide another way here:

arr.map{|h| {'a' => h['a'], 'c' => h['c'] } }
#=> [{"a"=>1, "c"=>3}, {"a"=>4, "c"=>6}, {"a"=>4, "c"=>6}]

Note that h here is a particular object of the array being iterated inside map, which is a Hash.

Bit more of a code to be typed though. You could use select as well.