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

Time:04-23

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",
      },
     ]

CodePudding user response:

you can do something like this

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

CodePudding user response:

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 }); 

CodePudding user response:

Simply add the index:

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