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
一样
正如@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)
您需要将
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,"