Reputation: 27
album.songs = [1234545, 43524];
const replaced = album.songs.map( e => { e = Object.assign({}, { _id : 123 }) } );
Output: undefined
My problem is that I would like to replace my items in 'songs' array with a specific object. It works with strings or numbers but not with objects.
Upvotes: 0
Views: 74
Reputation: 1074385
Some notes:
With map
, you return the object you want the new array to contain. Assigning to the parameter e
just changes the value of the parameter, which isn't retained anywhere.
There's no need for Object.assign
there, just create the object directly, so:
const replaced = album.songs.map(e => { return { _id : e }; } );
or the concise form:
const replaced = album.songs.map(e => ({ _id : e }) );
Note that since we want to return an object created with an object initializer, and the {
in the initializer would start a function body, we wrap the value we want to return in ()
.
We can even take advantage of shorthand property notation if we change the name of the parameter to _id
:
const replaced = album.songs.map(_id => ({ _id }) );
Live Example:
const album = {songs: [1234545, 43524]};
const replaced = album.songs.map(_id => ({ _id }) );
console.log(replaced);
Upvotes: 6
Reputation: 1748
Map function expects you to return a value for each iteration:
console.log([1, 2].map(n => n * 2))
In your case, it should be:
album.songs.map( e => ({ _id : e }))
Upvotes: 0
Reputation:
You don't assign to the function parameter, since it only exists for that function, and it's not like you're dereferencing a pointer.
Just return the object. An arrow function automatically returns its expression if you don't use curly braces to denote the body.
var songs = [1234545, 43524];
const replaced = songs.map(e => ({_id: e}));
console.log(replaced);
Upvotes: 0