Rails生成哈希数组

时间:2018-06-13 11:03:04

标签: ruby-on-rails arrays hash

我有一个数组,我想生成一个带有哈希的数组,并在该哈希内部再生一个数据。我有一个数据数组:

   [
        {
        id: 1,
        name:"abc"
        title:"xyz"
        },
        {
        id: 2,
        name:"abc1"
        title:"xyz1"
        },
   ]

我想生成这样的输出:

[
{        
    type: "column",
    dataPoints: [
    {y: 1, label: "abc"},
    {y: 2 ,label: "xyz"}
     ]
},
{        
    type: "column",
    dataPoints: [
    {y: 1, label: "abc1"},
    {y: 2 ,label: "xyz"}
    ]
 }         
]

如何使用map或任何数组循环创建这种数组哈希。我正在尝试为图表生成数据点。我正在寻找最好的解决方案。

1 个答案:

答案 0 :(得分:1)

其中一个选项:

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