You need to enable JavaScript to run this app. John Smilga的Comfy Store项目:JS解构丢失company属性问题排查
优惠活动
大模型
产品
解决方案
定价
更多

John Smilga的Comfy Store项目:JS解构丢失company属性问题排查

Comfy Store项目API解构后company属性不显示的问题排查与解决

问题背景

我正在做John Smilga的Comfy Store项目,用下面的代码从API解构数据:

let store = getStorageItem('store');
const setupStore = (products) => {
    store = products.map((product) => {
        const {
            id, 
            fields: { featured, name, price, company, colors, image:img },} = product;
        const image = img[0].thumbnails.large.url;
        return { id, featured, name, price, company, colors, image };
        
    });
    
    setStorageItem('store', store);
};
console.log(store);

运行console.log(store)后,除了company属性,其他请求的属性都正常显示,但API返回的数据里明明有company相关字段,想知道为啥这个属性不显示,怎么解决。

原因

JavaScript是大小写敏感的语言,从API返回的结构来看,company字段实际是首字母大写的Company,但你在解构的时候用了小写的company,匹配不到对应字段,所以返回的对象里company值为undefined,控制台自然不会显示这个属性(或显示为undefined)。

另外如果你的console.log(store)是在setupStore函数执行前调用的,那打印的是从本地存储取到的旧值,新的解构逻辑还没生效,也会出现company不显示的情况。

解决办法

  1. 修正解构的字段大小写:把解构里的company改成和API一致的Company,同时用别名保持返回对象里的属性名还是小写company:
let store = getStorageItem('store');
const setupStore = (products) => {
    store = products.map((product) => {
        const {
            id, 
            fields: { featured, name, price, Company: company, colors, image:img },
        } = product;
        const image = img[0].thumbnails.large.url;
        return { id, featured, name, price, company, colors, image };
        
    });
    
    setStorageItem('store', store);
};
  1. 确保执行顺序正确:先调用setupStore传入API获取到的产品数据,再打印store:
// 假设你已经从API拿到了products数据
setupStore(products);
console.log(store);

内容的提问来源于stack exchange,提问作者AllThingsShiny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:22:58