0

I'm currently struggling with a task, hope somebody can guide me in the right direction.

I have this array:

const data = [
{
  year: 2021,
  data: [
    { month: 'Jan', amount: 5000000 },
    { month: 'Feb', amount: 3500000 },
    { month: 'Mar', amount: 15000000 },
    { month: 'Apr', amount: 5000000},
    { month: 'May', amount: 3500000 },
    { month: 'Jun', amount: 15000000 },
    { month: 'Jul', amount: 13000000 },
    { month: 'Aug', amount: 20000000 }
  ]
},
{
  year: 2020,
  data: [
    { month: 'Jan', amount: 5000000 },
    { month: 'Feb', amount: 3500000 },
    { month: 'Mar', amount: 15000000 },
    { month: 'Apr', amount: 5000000},
    { month: 'May', amount: 3500000 },
    { month: 'Jun', amount: 15000000 },
    { month: 'Jul', amount: 13000000 },
    { month: 'Aug', amount: 20000000 }
  ]
}

]

And I'm trying to clean this so I can use HighCharts JS, which needs the following structure:

const data = [
  { year: '2021',
    data: [5000000, 3500000, 15000000, 5000000, 3500000, 15000000, 13000000, 20000000 ]
  },
  { year: '2020',
    data: [5000000, 3500000, 15000000, 5000000, 3500000, 15000000, 13000000, 20000000 ]
  }
]

So basically, is to clean the data array inside each object to get only the amount value without the month name. I tried doing a map and storage the result in a useState (I'm working with React JS) with no success.

Any idea would be highly appreciated.

2 Answers 2

3

Try this:

data.map(({ year, data: innerData }) => ({
   year,
   data: innerData.map(({ amount }) => amount)
}))
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I needed and very easy to read. Thanks so much!
2

You can map each object and replace the data array with a mapped data array inside a {...} spread

const data = [
{
  year: 2021,
  data: [
    { month: 'Jan', amount: 5000000 },
    { month: 'Feb', amount: 3500000 },
    { month: 'Mar', amount: 15000000 },
    { month: 'Apr', amount: 5000000},
    { month: 'May', amount: 3500000 },
    { month: 'Jun', amount: 15000000 },
    { month: 'Jul', amount: 13000000 },
    { month: 'Aug', amount: 20000000 }
  ]
},
{
  year: 2020,
  data: [
    { month: 'Jan', amount: 5000000 },
    { month: 'Feb', amount: 3500000 },
    { month: 'Mar', amount: 15000000 },
    { month: 'Apr', amount: 5000000},
    { month: 'May', amount: 3500000 },
    { month: 'Jun', amount: 15000000 },
    { month: 'Jul', amount: 13000000 },
    { month: 'Aug', amount: 20000000 }
  ]
}]

const newdata = data.map(e=> ({...e, data: e.data.map(x=>x.amount)}))
console.log(newdata)

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.