Reputation: 5909
I want to map an array, returning the same array except .created
property, that I'm transforming from milliseconds to Date Object.
const posts = data.map((post) => {
post.created = new Date(post.created); //milliseconds to Date Object
return post;
})
This function do the result that I expected, but I don't like because the function inside is not pure, is mutating the object. How can be an alternative to do the same with pure function?
Thank you so much.
Upvotes: 1
Views: 77
Reputation: 67296
You can achieve this using Object.assign
(docs) inside the map
:
const posts = data.map((post) => {
return Object.assign({}, post, { created: new Date(post.created) });
})
This essentially clones the original post
and then overrides the created
property.
Upvotes: 2
Reputation: 48745
You can make copy without copying all of the attributes from the old object:
const posts = data.map((post) => {
const obj = Object.create(post);
obj.created = new Date(post.created); // shadow created with the new value
return obj;
});
In practice it uses JavaScript inheritance scheme so that the new object only has created
as it's own attribute and the rest is inherited from the original object.
Upvotes: 1
Reputation: 14866
I would provide both solutions.
data.map(post => Object.assign({created: new Date(post.created)},post));
The first argument of Object.assign
is the target
object. It's also the object that Object.assign
returns.
for(let post of data){
post.created = new Date(post.created);
}
This method is, of course, faster and costs less resources since it doesn't need to initialize a new array and its objects then copy all objects' properties like the other does.
The choice is yours. Just make sure you know what you're doing.
Upvotes: 1