Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

To add a property in an object in typescript, You can use dot, colon, or bracket syntax but if you want to add a property letter in the object then you have to define optional property using question mark ( ? ) syntax.

To transfer data from one file to another, or project to another we used JSON i.e we need many times to add data in JSON objects statically, and dynamically.

Today, we will see how to add elements to an object and also how many ways to do that in typescript with example.

let’s start with when we create a new object.

Create an object with key-value pair

When we create a new object we mainly use {} curly brace to create and when we want to create an object with value. we follow the below code.

interface User {
  id: number;
  name: string;
  domain?: string;
  age?: number;
  isActive?: boolean;
}

let user: User = {
  id: 1,
  name: "infinitbility",
};

Add element in already created object statically

let’s assume we already created the object now we want to add more elements to it then we will follow the below code.

interface User {
  id: number;
  name: string;
  domain?: string;
  age?: number;
  isActive?: boolean;
}

let user: User = {
  id: 1,
  name: "infinitbility",
};


//  Add element using key
user.domain = "infinitbility.com";
console.log("user", user);

Add element in already created object dynamically

Now, many times we have to add elements in already create objects dynamically, for dynamic we have the option below code example.

interface User {
  id: number;
  name: string;
  domain?: string;
  age?: number;
  isActive?: boolean;
}

let user: User = {
  id: 1,
  name: "infinitbility",
};

// Add element for dynamic key
user["isActive"] = true;
console.log("user", user);

Output

TypeScript, add, element, object, example
TypeScript, add key-value pair in json object example.

Thanks for reading…