SamCodes
SamCodes

Reputation: 394

create json without duplicate value in typescript

I'd like to create a JSON in typescript. JSON array would look like this: JsonArray = [{k1:v1},{k2:v2},{k3:v3}...]

This function add items to Json Array

myfunc(keyName, valueName){
   this.JsonArray.push({
     [keyName] : valueName;        
   })
}

And this below function calls the above function:

createJsonArray(keyName, valueName){
   if(//keyName already exists in this.JsonArray){
     //update the value for the keyName this.JsonArray
   }
   else
      this.myfunc(keyName, valueName);
}

Though I have tried with some stack-overflow hints but I'm getting stuck these // segment.

How to write those part to update the json array?

Upvotes: 0

Views: 51

Answers (1)

Rodris
Rodris

Reputation: 2848

Find the item and check if it is valid.

class A {
    private JsonArray = [];

    myfunc(keyName, valueName){
        this.JsonArray.push({
            [keyName] : valueName        
        })
    }

    createJsonArray(keyName, valueName) {
        let item = this.JsonArray.find((item) => item[keyName]);

        if (item) {
            item[keyName] = valueName;
        }
        else {
            this.myfunc(keyName, valueName);
        }
    }
}

Upvotes: 1

Related Questions