Hi Friends 👋,

Welcome To Infinitbility! ❤️

To set value in JSON object in javascript, we have multiple ways

  1. Set the value at the time of creating JSON object
  2. Set value using the key in JSON object
  3. Set value using dynamic key in JSON object

Let’s take a short example of all the above methods.

// Set value at the time of creating JSON object
let obj = {
    id: 1
}

// Set value using key in json object
obj.name = "infinitbility";

// Set value using dynamic key in JSON object
let key = "status";
obj[key] = true;

console.log(obj)
// 👇️ Output
//  { id: 1, name: 'infinitbility', status: true }

Today, I’m going to show you How do I set value in a JSON object in javascript, as above mentioned, I’m going to use all the above-mentioned methods.

Let’s start today’s tutorial how do you assign value in a JSON object in javascript?

Set value at the time of creating JSON object

To set value at the time of the creation of an object, we have colon syntax to write key and value.

In this example, I’m creating an object with id key-value pair.

let obj = {
    id: 1
}

console.log(obj)
// 👇️ Output
//  { id: 1 }

Set value using the key in a JSON object

To set the value using the key in javascript, javascript provide dot syntax, using this syntax we can create key-value pair in exiting JSON object.

In this below example, we have used the above existing object and added new key-value pair using dot syntax.

let obj = {
    id: 1
}

obj.name = "infinitbility";

// 👇️ Output
//  { id: 1, name: 'infinitbility' }

Set value using the dynamic key in a JSON object

To value using the dynamic key in a JSON object, javascript provides bracket syntax where we have to mention the key in the bracket and equal to value.

In this below example, we have created a key variable and used it for creating key-value pair in JSON object.

let obj = {
    id: 1
}

let key = "status";
obj[key] = true;

console.log(obj)

I hope it helps you, All the best 👍.