[英]Traversing recursively through an array and modifying values of object properties in JavaScript
[英]Modifying JavaScript array properties
我正在使用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
的查詢和使用,這兩個都使“故事” .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);
正如其他人指出的那樣,您正在濫用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)}))
您可能想考慮forEach()
:
stories.forEach(story => {
story.created = dateFormat(story.created, "dddd, mmmm dS, yyyy, h:MM:ss TT")
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.