0

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.

1
  • This doesn't make any sense as of now. Can you explain the logic of how to reach from input to output given in the question? Commented Jun 13, 2018 at 11:24

1 Answer 1

1

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] } } } }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.