2017-03-21 328 views
0

我有對象的嵌套陣列的陣列,其中我需要格式化屬性中的每個對象映射整數數組對象

const myMap = { 
    '1': 
    [ { date: '2016-03-10T00:00:00', location: 'NV' }, 
    { date: '2016-03-10T00:00:00', location: 'WV' }, 
    { date: '2016-03-10T00:00:00', location: 'CA' } ], 
    '2': 
    [ { date: '2016-03-10T00:00:00', location: 'NJ' }, 
    { date: '2016-03-10T00:00:00', location: 'PA' } ], 
    '3': 
    [ { date: '2016-03-10T00:00:00', location: 'WA' }, 
    { date: '2016-03-10T00:00:00', location: 'NH' }, 
    { date: '2016-03-10T00:00:00', location: 'CA' } ] 
} 

我目前使用lodash和moment.js

有這樣的代碼
var _ = require('lodash') 
var moment = require('moment') 

_.map(myMap["date"], (a) => { moment(a).format('DD MMM YYYY') }) 
console.log(myMap) 
// [] 

它目前返回一個空數組,我將如何格式化每個日期而不改變格式?

回答

2

既然您正在處理一個Object,並且您想要更改其中的值,則需要使用Lodash的_.mapValues()函數(_.map()用於數組)。

const myMap = { 
 
     '1': 
 
     [ { date: '2016-03-10T00:00:00', location: 'NV' }, 
 
     { date: '2016-03-10T00:00:00', location: 'WV' }, 
 
     { date: '2016-03-10T00:00:00', location: 'CA' } ], 
 
     '2': 
 
     [ { date: '2016-03-10T00:00:00', location: 'NJ' }, 
 
     { date: '2016-03-10T00:00:00', location: 'PA' } ], 
 
     '3': 
 
     [ { date: '2016-03-10T00:00:00', location: 'WA' }, 
 
     { date: '2016-03-10T00:00:00', location: 'NH' }, 
 
     { date: '2016-03-10T00:00:00', location: 'CA' } ] 
 
    }; 
 

 
    function formatDates(arr) { 
 
     return _.map(arr, formatDate); //map each element of array using formatDate 
 
    } 
 

 
    function formatDate(data) { //copy and format data to new object for mapping 
 
     let formattedData = {}; 
 
     formattedData.date = moment(data.date).format('DD MMM YYYY'); 
 
     formattedData.location = data.location; 
 
     
 
     return formattedData; 
 
    } 
 

 
    let result = _.mapValues(myMap, formatDates); //iterate thru each key in object and update values 
 

 
    console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>