Skip to content

Add key value to object JavaScript

  • by

Using Dot Notation or Square Bracket Notation you can Add key values to objects in JavaScript.

// dot
obj.property = value;

// brakcet
obj[property] = value;

Add key value to object JavaScript

Simple example code add a key/value pair to an object.

<!DOCTYPE html>
<html>
<body>
  <script>
    const person = {
      name: 'John',
      age: 22,
      active: true
    }
    console.log(person)

    // Dot
    person.height = 5.4;
    console.log(person);

    // Bracket
    person['Salary'] = 100;
    console.log(person);

  </script>
</body>
</html>

Output:

Add key value to object JavaScript

How to add a dynamic key with value in an existing Javascript object?

Answer: You can do this with Object.assign() and using Computed Property names (example {[key]: value}):

let existingObject = {
    1: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
    2: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
    3: {'prop1': 'prop1 value', 'prop2': 'prop2 value'}
}

const key = 4;
const value = {'prop1': 'prop1 value', 'prop2': 'prop2 value'}

Object.assign(existingObject, {[key]: value});
console.log(existingObject);

Output:

{
  "1": {
    "prop1": "prop1 value",
    "prop2": "prop2 value"
  },
  "2": {
    "prop1": "prop1 value",
    "prop2": "prop2 value"
  },
  "3": {
    "prop1": "prop1 value",
    "prop2": "prop2 value"
  },
  "4": {
    "prop1": "prop1 value",
    "prop2": "prop2 value"
  }
}

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading