EN
TypeScript - add key / value pair to object
0 points
In this article, we would like to show you how to add key / value pair to an object in TypeScript.
In the below example we create object
with two key / value pairs.
We add key3
with 'value3'
using square bracket notation, then we display whole object
.
Note:
This approach is useful because you can replace'key3'
string with some variable which let us address key value dynamically using variable.
Runnable example:
xxxxxxxxxx
1
interface MyObject {
2
key1: string;
3
key2: string;
4
}
5
6
const object: MyObject = {
7
key1: 'value1',
8
key2: 'value2',
9
};
10
11
object['key3'] = 'value3';
12
13
console.log(JSON.stringify(object, undefined, 4));
Output:
xxxxxxxxxx
1
{
2
"key1": "value1",
3
"key2": "value2",
4
"key3": "value3"
5
}