我有一个嵌套的对象数组,我需要在每个对象中格式化一个属性
Object item
我目前使用lodash和moment.js
获取此代码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' } ]
}
它当前返回一个空数组,如何格式化每个日期而不更改格式?
答案 0 :(得分: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>