'How do I use map function, so I can add the index as a property to the newly constructed object?

I have an array of indexes: selected = [2, 6, 10] () for instance. I also have array of photo objects called photos. I want to keep track of only selected photos so I do :

const selectedPhotos = selectedArray.map((i) => photos[i]); 

Which gives me the result:

Array [
  Object {
    "albumId": "someId1",
    "creationTime": "sometime",
    "duration": 0,
    "filename": "name1.jpg",
    "id": "someId1",
    "uri": "someIUri1",
  },
  Object {
    "albumId": "someId2",
    "creationTime": "sometime",
    "duration": 0,
    "filename": "name2.jpg",
    "id": "id2",
    "uri": "uri2",
  },
  Object {
    "albumId": "someId3",
    "creationTime": "sometime",
    "filename": "filename3.jpg",
    "uri": "uri3",
  },
 ]

Which is good, BUT I also want to keep track of the selected index. So my question is, how should I add something like the following information: index: 2, or index: 6, etc alongside the photo properties. So I want to return something like:

Array [
      Object {
        "index": 2,
        "albumId": "someId1",
        "creationTime": "sometime",
        "duration": 0,
        "filename": "name1.jpg",
        "id": "someId1",
        "uri": "someIUri1",
      },
      Object {
        "index": 6
        "albumId": "someId2",
        "creationTime": "sometime",
        "duration": 0,
        "filename": "name2.jpg",
        "id": "id2",
        "uri": "uri2",
      },
      Object {
        "index": 10
        "albumId": "someId3",
        "creationTime": "sometime",
        "filename": "filename3.jpg",
        "uri": "uri3",
      },
     ]


Solution 1:[1]

you can do something like this

const selectedPhotos = selectedArray.map((i) => {
 let curItem={...photos[i]};
 curItem.index=i;
  return curItem;
}); 

Solution 2:[2]

Simply add the index:

const selectedPhotos = selectedArray.map((i) => {
  let photo = photos[i];
  photo.index = i;
  return photo;
}); 

Solution 3:[3]

You can create a new object and destructure the one you want inside of it, then add the index. That way you can do it in one line and it's easy to read.

const selectedPhotos = selectedArray.map(i => ({ ...photos[i], index: i })); 

Safer version with optional chaning:

const selectedPhotos = selectedArray.map(i => ({ ...photos?.[i], index: i })); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jatin Parmar
Solution 2
Solution 3