简体   繁体   中英

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.

You can use _.map like below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM