Add new attribute (element) to JSON object using JavaScript
Directly add an attribute to a JSON object by creating a key-value pair. Given the JSON object myObj
, add newKey
with the value newValue
:
For dynamic keys or keys with special characters, use brackets:
This modifies myObj
directly:
JSON - Not just a pretty string
JSON (JavaScript Object Notation) is a data interchange format often represented as a string. When manipulating JSON in JavaScript, you'll need to convert it into a JavaScript object before adding new attributes.
JSON.parse(jsonString) converts the JSON string to a JavaScript object. Once this transformation is done, addition of new attributes is a piece of cake.
Spread the joy with spread syntax
For those preferring a functional programming approach or immutable data patterns, you might like spread syntax:
This creates a new object without playing with the original (oldObj
). Oh, and it adds the newProperty
too!
Special characters and reserved words
For keys that may be reserved words or have special characters, use the bracket syntax to avoid accidents:
It helps you avoid syntax errors in not-so-friendly browsers like Internet Explorer.
Using variables to access properties
It's way efficient when your key name is a variable. You can dynamically assign keys and values to an object like this:
Think Big Data
Work on large-scale data structures while adding new attributes needs some care. An added attribute might introduce:
- Unforeseen side effects if other functions are counting on the previous object shape.
- Performance issues due to adding properties to large arrays.
- Changes that make maintaining data integrity difficult.
Before hitting that save button, make sure to check the whole object structure.
Clear & maintainable code
Here is a quick-to-follow list to keep your code maintainable:
- Use dot notation where you can for readability.
- When hard to avoid, use bracket notation for reserved words.
- Contemplate restructuring the JSON object if it simplifies the data model.
- Exclude any browser-specific syntax issues.
- Make sure the changes done are for the good by thorough testing.
Good practices to keep data intact
Post modifying a JSON object, make sure to:
- Review the object structure. Always.
- Test the JSON so as to not break the application logic.
- Keep an eye on ESLint rules to retain code quality.
Was this article helpful?