我使用Express并拥有一组对象。我想修改created
属性(我正在使用dateFormat包)进行演示。
该数组是mongo查询的结果,并分配给变量stories
,如下所示:
[
{ public: false,
keyStageLevel: [ 'ks1' ],
created: 2018-03-25T13:01:30.809Z,
_id: 5ab79daafa832035b416536f,
slug: 'goldilocks',
name: 'Goldilocks',
comments: null,
id: '5ab79daafa832035b416536f' },
{ public: false,
keyStageLevel: [ 'ks1' ],
created: 2018-03-25T13:07:22.421Z,
_id: 5ab79f0afa832035b4165370,
slug: 'cinderella',
name: 'Cinderella',
comments: null,
id: '5ab79f0afa832035b4165370' },
..
]
如果我执行
stories.map(function(story){
story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
console.log('AFTER TRANSFORM '+story.created);
});
console.log显示了我想要的日期格式,但story.created
数组中的stories
值未经修改。什么是正确的方法(ES5,如果可能,我学习并且我发现更容易理解发生了什么)重新格式化created
数组中的stories
属性?
修改 - 显示.map
和.foreach
的查询和使用,两者都会留下“故事”。未修饰的
let stories = await Story.find({$or:[{'group': {$in:group}},
{'public':true} ]})
.populate('group')
.populate('createdBy');
console.log('BEFORE TRANSFORM '+stories);
// console.log(stories);
// stories.map(function(story){
// story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
// console.log('AFTER TRANSFORM '+story.created);
// });
stories.forEach(story => {
story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
});
console.log('AFTER TRANSFORM '+stories);
答案 0 :(得分:2)
正如其他人所说,您误导map
。不过,我的选择是正确使用map
,并从旧版本中创建一个新数组。我认为对未发生变异的数据进行推理要容易得多。这是一种方法:
const stories = [{"_id": "5ab79daafa832035b416536f", "comments": null, "created": "2018-03-25T13:01:30.809Z", "id": "5ab79daafa832035b416536f", "keyStageLevel": ["ks1"], "name": "Goldilocks", "public": false, "slug": "goldilocks"}, {"_id": "5ab79f0afa832035b4165370", "comments": null, "created": "2018-03-25T13:07:22.421Z", "id": "5ab79f0afa832035b4165370", "keyStageLevel": ["ks1"], "name": "Cinderella", "public": false, "slug": "cinderella"}]
const dateFormat = (d) => d.slice(0, 10) // dummy
const updatedStories =
stories.map(story => ({...story, created: dateFormat(story.created)}))
console.log(updatedStories)

如果ES6困扰你,那么你可以用
替换它stories.map(story => Object.assign({}, story, {created: dateFormat(story.created)}))
答案 1 :(得分:-1)
您可能需要考虑forEach()
:
stories.forEach(story => {
story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
});