Reputation: 394
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
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