Algorithm


Algorithm AddKeyValuePairToObject(obj, key, value):
    1. Check if obj is an object
        a. If not, throw an error or handle appropriately
    2. Add the key/value pair to obj
        a. Set obj[key] = value
    3. Return obj

Code Examples

#1 Code Example- Add Key/Value Pair to an Object Using Dot Notation

Code - Javascript Programming

// program to add a key/value pair to an object

const person = {
    name: 'Akash',
    age: 22,
    gender: 'female'
}

// add a key/value pair
person.height = 5.4;

console.log(person);
Copy The Code & Try With Live Editor

Output

x
+
cmd
{
name: "Akash",
age: 22,
gender: "female",
height: 5.4
}

#2 Code Example- Add Key/Value Pair to an Object Using Square Bracket Notation

Code - Javascript Programming

// program to add a key/value pair to an object

const person = {
    name: 'Akash',
    age: 22,
    gender: 'female'
}

// add a key/value pair
person['height'] = 5.4;

console.log(person);
Copy The Code & Try With Live Editor

Output

x
+
cmd
{
name: "Akash",
age: 22,
gender: "female",
height: 5.4
}
Advertisements

Demonstration


JavaScript Program Example to Add Key/Value Pair to an Object-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way