简体   繁体   English

如何在 Angular Typescript 中的嵌套字典键中添加另一个值

[英]How to add another value to nested dictionary key in Angular Typescript

I have a dictionary that looks like this and I want to add one more value to "model1" key我有一本看起来像这样的字典,我想向“model1”键添加一个值

variants= {"model1" : {"orange":2} }

I want to make it look like this:我想让它看起来像这样:

variants= {"model1" : {"orange":2, "black":1} }

What's the code for that?那是什么代码? thanks谢谢

The best way I can suggest is:我可以建议的最好方法是:

variants.model1 = Object.assign({}, variants.model1, {"black":1})

That would be better if you add a property check before it to be sure that model1 exists in the variants.如果您在它之前添加一个属性检查以确保model1存在于变体中,那会更好。 You can write a function like this:您可以像这样编写 function:

addToDictionary(variants, key, value) {
    if(variants.hasOwnProperty(key) {
        variants[key] = Object.assign({}, variants[key], value);
    } else {
        variants[key] = value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建带有角度键/值对的字典? - How to create a Dictionary with Key/Value pairs in angular? Angular 2,使用打字稿创建字典 <key, value> 并加载json文件以将数据放入其中 - Angular 2 , create dictionary using typescript <key, value> and load json file to put data in it 如何将选定的项目添加到打字稿中的另一个多重选择中(Angular 4项目) - How to add the selected items to another multiple select in typescript (Angular 4 project) Angular 8 Typescript 如何从另一个组件设置导出常量的值? - Angular 8 Typescript How to set value of export const from another component? 如何将 html 元素添加到数组 JSON、Typescript、ZC31C335EF37283C1Z1B18 中的值 - How to add a html element to Value in Array JSON, Typescript, Angular 如何将 Typescript 变量值添加到 Angular div 标签? - How add Typescript variable value to Angular div tag? 如何在Angular2中为嵌套对象内的键动态设置值 - How to set dynamically value for key inside nested object in Angular2 如何访问 Angular 中 Json 中的嵌套键值对 - How to access the nested key value pairs in a Json in Angular Angular/Typescript:如何在键值对中返回枚举键而不是值? - Angular/Typescript: How to return enum key instead of value in a key-value pair? Angular TypeScript Map 键值对不保存 - Angular TypeScript Map with key value pairs not saving
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM