Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lodash: replace value in array of objects

To replace value in array of objects, and in this case the created_at with ‘jan’, ‘Feb’ etc, I can certainly use map through as shown below.

But is there a shorter way using lodash?

import React, { useEffect } from 'react'
import _ from 'lodash'
import moment from 'moment'

interface DataProps {
  clazz_name: string
  created_at: string
}

const dataone: DataProps[] = [
  {
    clazz_name: '1A',
    created_at: '2022-01-19T09:13:42.149+08:00',
  },
  {
    clazz_name: '1B',
    created_at: '2022-02-19T09:13:42.149+08:00',
  },
]

let datatwo: DataProps[] = []

function App() {
  useEffect(() => {
    dataone.forEach((item) =>
      datatwo.push({
        clazz_name: item.clazz_name,
        created_at: moment(item.created_at).format('MMM'),
      })
    )
    console.log(datatwo)
  }, [])

  return <div>Test</div>
}

export default App

Any hint or help would be greatly appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use _.map like below

const dataTwo = _.map(dataOne, item => ({...item, created_at: moment(item.created_at).format('MMM') }))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading