Search code examples
javascriptreact-nativeecmascript-6lodashspread-syntax

Reformatting map values and updating with spread syntax


I'm trying to format the object properties within an array. I'm having some trouble as The following code throws the following error but the react native throws TypeError: In this environment the sources for assign MUST be an object.This error is a performance optimization and not spec compliant. <<< path/to/project/node_modules/react-native/packager/src/Resolver/polyfills/polyfills.js

const objArr = [ 
   { event.date: '2016-03-10T00:00:00', event.location: 'NV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'WV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'CA' } 
],

const formatDate = (data) => {
  const formattedDate = moment(data['event.start_date']).format('DD MMM YYYY');

  return { ...data, data['event.start_date']: formattedDate } };
}

const formatDates = (arr) => { return _.map(arr, formatDate) }

let result = _.map(objArr, formatDates);

How would i change the event.date to the formatted data without touching the rest of the object? In reality have many variables I would like to pass over, and don't think individually assigning each to a new object is best.

How should I go about this? Any help / tips appreciated!


Solution

  • You seem to be grossly overcomplicating the task by using several maps.

    If you simplify the problem, you should be able to do this:

    const objArr = [ 
      { 'event.date': '2016-03-10T00:00:00', 'event.location': 'NV' },
      { 'event.date': '2016-03-10T00:00:00', 'event.location': 'WV' },
      { 'event.date': '2016-03-10T00:00:00', 'event.location': 'CA' } 
    ];
    
    const result = objArr.map((event) => ({
      ...event,
      'event.start_date': moment(event['event.start_date']).format('DD MMM YYYY'),
    }));
    
    console.log(result);