Reputation: 2331
I have an array and I want to generate an array with hash and inside that hash one more data. I have a data array which is:
[
{
id: 1,
name:"abc"
title:"xyz"
},
{
id: 2,
name:"abc1"
title:"xyz1"
},
]
And I want to generate an output like this:
[
{
type: "column",
dataPoints: [
{y: 1, label: "abc"},
{y: 2 ,label: "xyz"}
]
},
{
type: "column",
dataPoints: [
{y: 1, label: "abc1"},
{y: 2 ,label: "xyz"}
]
}
]
How create this kind of array hash using map or any array loop. I am trying to generate data points for charts. I am looking for best possible solution.
Upvotes: 0
Views: 92
Reputation: 1404
One of the options:
array = [
{
id: 1,
name:"abc",
title:"xyz"
},
{
id: 2,
name:"abc1",
title:"xyz1"
}
]
[:name, :title].map do |column_name|
{
type: 'column',
dataPoints: array.map do |el|
{ y: el[:id], label: el[column_name] }
end
}
end
# or in one line:
[:name, :title].map { |column_name| { type: 'column', dataPoints: array.map { |el| { y: el[:id], label: el[column_name] } } } }
Upvotes: 1