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
相关产品推荐
相关产品推荐

