[英]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.