Hackensack
Hackensack

Reputation: 27

How can I replace an item in an array with an object?

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

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Some notes:

  1. 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.

  2. 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 ().

  3. 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

Ramon Diogo
Ramon Diogo

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

user9366559
user9366559

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

Related Questions