I'm using Express and have an array of objects. I would like to modify the created property (I am using dateFormat package) for presentation.
The array is the result of a mongo query and is assigned to a variable stories and looks like:
[
{ 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' },
..
]
If I execute
stories.map(function(story){
story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
console.log('AFTER TRANSFORM '+story.created);
});
The console.log shows the date format I want but the story.created values in the stories array is unmodified. What is the correct way (ES5 if possible, I'm learning and I find it easier to understand what is going on) to reformat the created property in the stories array?
Edit - showing the query and use of .map and .foreach both of which leave `stories' unmodified
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);
.mapexpects areturnvalue - do aforEach-stories.forEach(function(story){stories.mapto a variable, where and how do you check the values in thestories? Create a minimal and reproducable example..forEachshoudl be use here. But it would not explain the problem the OP has. Because if the OP would dostories = stories.mapthenstorieswould be an array containing onlyundefined, but the OP says that the values are unchanged. And if the OP really wrotestories.mapwithout asigning the new array to a variable, then result ofstories.mapandstories.forEach, would be the same.