Cameron
Cameron

Reputation: 28783

Create new array of arrays from key

I have an array:

[{
    "name": "Category 1",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}, {
    "name": "Category 2",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}]

What I want to do is create a new array of just the entries.

So I end up with this:

[{
    "question": "Question 1",
    "answer": "Answer 1"
}, {
    "question": "Question 2",
    "answer": "Answer 2"
}, {
    "question": "Question 3",
    "answer": "Answer 3"
}, {
    "question": "Question 1",
    "answer": "Answer 1"
}, {
    "question": "Question 2",
    "answer": "Answer 2"
}, {
    "question": "Question 3",
    "answer": "Answer 3"
}]

In PHP I would of just do a push into a new array... but in Ruby is it possible to use group_by or collect to achieve this?

Upvotes: 1

Views: 96

Answers (2)

dp7
dp7

Reputation: 6749

map and flatten would give you desired output:

your_array.map {|hash| hash[:entries]}.flatten

#=> [{:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"},
# {:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"}]

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52357

Use Enumerable#flat_map:

array = [{
    "name": "Category 1",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}, {
    "name": "Category 2",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}]
array.flat_map { |hash| hash[:entries] }
   #=> [{:question=>"Question 1", :answer=>"Answer 1"},
   #  {:question=>"Question 2", :answer=>"Answer 2"},
   #  {:question=>"Question 3", :answer=>"Answer 3"},
   #  {:question=>"Question 1", :answer=>"Answer 1"},
   #  {:question=>"Question 2", :answer=>"Answer 2"},
   #  {:question=>"Question 3", :answer=>"Answer 3"}]

Upvotes: 7

Related Questions