这段代码按预期更改了图像,但没有更改 id?

问题描述 投票:0回答:2
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)

当我打印

155
时,我期望id从
5542
更改为
processedResults[0].id
(它打印旧值
155
),就像我打印
some image string时图像从
data:image/png;base64,
更改为
processedResults[0].image
一样

javascript arrays object debugging mapping
2个回答
0
投票

正如@Antonia Šimić 提到的,尝试一下;

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

const processedResults = currentTypesResult.map((item) => {
   
const { id, foodId, image, ...rest } = item;

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

console.log(processedResults[0].id) 
console.log(processedResults[0].image) 


0
投票

您需要将

rest
放在
id
属性之前,否则
id
将被覆盖,因为它已经是
rest
的一部分。这是工作代码示例:

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,"
© www.soinside.com 2019 - 2024. All rights reserved.