gpt4 book ai didi

javascript - 将整数数组映射到对象数组

转载 作者:行者123 更新时间:2023-12-01 03:53:53 25 4
gpt4 key购买 nike

我有一个嵌套的对象数组,我需要在其中格式化每个对象的属性

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)
// []

它当前返回一个空数组,如何在不更改格式的情况下格式化每个日期?

最佳答案

由于您正在处理一个 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>

关于javascript - 将整数数组映射到对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com