You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何创建不存在的对象键?解决TypeError报错

问题解决:Uncaught TypeError: Cannot set properties of undefined (setting 'quantity')

你遇到的错误是因为cart初始为空对象,直接访问cart[key]时该键对应的属性未定义(值为undefined),无法直接给它的子属性赋值。以下是几种实现"不存在则自动创建cart[newKey]"的方案:

方案一:先初始化空对象再赋值

在给子属性赋值前,确保cart[key]是一个对象,不存在则创建空对象:

$.ajax({
    url: "/cart/sync",
    success: function(response){
        let cart = {};
        Object.keys(response).forEach(key => {
            // 若cart[key]不存在则初始化为空对象
            cart[key] = cart[key] || {};
            cart[key].quantity = response[key].product_quantity;
            cart[key].discounted_price = response[key].product_discounted_price;
            cart[key].holding = response[key].product_temp_holding;
        });
    }
});

方案二:直接赋值完整对象(推荐)

既然是从response[key]提取属性构建cart[key],直接将属性打包成对象赋值,无需额外初始化:

$.ajax({
    url: "/cart/sync",
    success: function(response){
        let cart = {};
        Object.keys(response).forEach(key => {
            cart[key] = {
                quantity: response[key].product_quantity,
                discounted_price: response[key].product_discounted_price,
                holding: response[key].product_temp_holding
            };
        });
    }
});

方案三:用Object.assign合并属性

如果cart[key]可能已存在部分属性,需要保留原有属性并添加新属性,可使用Object.assign:

$.ajax({
    url: "/cart/sync",
    success: function(response){
        let cart = {};
        Object.keys(response).forEach(key => {
            // 合并现有属性(若存在)和新属性
            cart[key] = Object.assign(cart[key] || {}, {
                quantity: response[key].product_quantity,
                discounted_price: response[key].product_discounted_price,
                holding: response[key].product_temp_holding
            });
        });
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:35:23