skip to Main Content
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

2

Answers


  1. As mentioned by @Antonia Šimić, give this a try;

    const currentTypesResult=[{id:'155', foodId:'511555522559744444', image: 'Some image string', example:'example'}]
    
    const processedResults = currentTypesResult.map((item) => {
       
    const { id, foodId, image } = item;
    
    return {
    id: 5542,
    image: 'data:image/png;base64,',
    };
    });
    
    console.log(processedResults[0].id) 
    console.log(processedResults[0].image) 
    Login or Signup to reply.
  2. 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,"
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search