为何JS代码中image已更新但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)
问题原因:
这是对象属性赋值顺序导致的覆盖问题:
- 解构
item时,你只排除了foodId和image,所以...rest里包含了原对象的id: '155',rest的实际结构是{id: '155', example: 'example'}。 - 返回对象时,你先声明了
id: '5542',随后用...rest展开旧属性——对象中后声明的属性会覆盖先声明的同名属性,所以rest里的旧id直接覆盖了你刚设置的新id。 - 而
image能正常更新,是因为它已经被排除在rest之外,展开rest时不会出现同名属性覆盖的情况。
修复方案:
有两种常见的解决方式:
方式一:调整展开顺序,先放旧属性再覆盖
把...rest放在前面,再声明要修改的属性,让新属性覆盖旧值:
const processedResults = currentTypesResult.map((item) => { const { foodId, image, ...rest } = item; return { ...rest, id: '5542', image: 'data:image/png;base64,' }; });
方式二:解构时单独提取id,不让它进入rest
直接把id从item中解构出来,这样rest里就不会包含旧id,后续展开也不会覆盖新值:
const processedResults = currentTypesResult.map((item) => { const { foodId, image, id, ...rest } = item; return { id: '5542', image: 'data:image/png;base64,', ...rest }; });
执行上述任意一种修改后,processedResults[0].id就会输出预期的5542了。
内容的提问来源于stack exchange,提问作者Majd
相关产品推荐
相关产品推荐

