javascriptarraysobjectdebuggingmapping

This code changing the image as expected but not the id?


const currentTypesResult = [{
  id: '155',
  foodId: '511555522559744444',
  image: 'Some image string',
  example: 'example'
}]

const processedResults = currentTypesResult.map((item) => {

  const {
    foodId,
    image,
    ...rest
  } = item;

  return {
    id: '5542',
    image: 'data:image/png;base64,',
    ...rest
  };
});

console.log(processedResults[0].id) // Prints 155? Why? Why not 5542?
console.log(processedResults[0].image) // Prints data:image/png;base64, (AS IT SHOULD)

I'm expecting id to change from 155 to 5542 when I print processedResults[0].id (It prints the old value 155) just like image was changed from some image string to data:image/png;base64, when I printed processedResults[0].image


Solution

  • You need to put the rest before the id property otherwise the id will get overwritten since it is already a part of the rest. Here is the working code example:

    const currentTypesResult = [
      { id: '155', foodId: '511555522559744444', image: 'Some image string', example: 'example' }
    ];
    
    const processedResults = currentTypesResult.map((item) => {
      const { foodId, image, ...rest } = item;
    
      return {
        ...rest, 
        id: "whatever you like",
        image: 'data:image/png;base64,'
      };
    });
    
    console.log(processedResults[0].id); // Now it should print 'whatever you like'
    console.log(processedResults[0].image); // Should print "data:image/png;base64,"