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

Angular 12中如何创建含动态键值对的字典对象

Angular中创建动态键的字典对象实现方案

你的代码问题在于使用了字符串字面量'${keya}'作为键,这会把${keya}当成固定字符串,而不是变量keya的实际值。要创建带动态键的字典对象,有两种常用实现方式:

方法一:使用ES6计算属性名

直接在对象字面量中用方括号包裹变量,就能将变量值作为对象的键:

private createCartItem(id: number, quantity: number) {
    const keya =  `addtocart_${id}.EnteredQuantity`; // 用模板字符串简化字符串拼接
    const dictionary = { [keya]: quantity };
    return dictionary;
}

方法二:先创建空对象再动态赋值

先初始化空对象,再通过方括号语法给对象添加动态键值对:

private createCartItem(id: number, quantity: number) {
    const keya =  'addtocart_' + id + '.EnteredQuantity';
    const dictionary = {};
    dictionary[keya] = quantity;
    return dictionary;
}

两种方法都能生成符合需求的键值对对象,可直接作为HTTP POST请求体发送给Web API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:00:49