[Fixed] 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

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. You can write a function like this:

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

Leave a Reply

(*) Required, Your email will not be published