7+ Ways to Conditionally Add Properties to JS Objects

conditionally add property to object javascript

7+ Ways to Conditionally Add Properties to JS Objects

Dynamically augmenting JavaScript objects with properties primarily based on particular standards is a basic side of object manipulation. This includes evaluating a situation and, if met, introducing a brand new property-value pair to the item. For example, think about an object representing a person. A “verified” property is likely to be added provided that sure authentication checks cross. This may be achieved by numerous means, equivalent to utilizing `if` statements, ternary operators, or much more complicated logic involving loops and features. A easy instance could be:

javascript let person = { title: “John Doe” }; let isAuthenticated = true; if (isAuthenticated) { person.verified = true; } console.log(person); // Output: { title: “John Doe”, verified: true }

Read more