An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
3 ways to add conditional properties to an object [...]
What is Spread Operatot?
source: MDN
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Example:-
{ ...(someCondition && {a: hi})}
Or
const greed = { ...(true) && {a: hi}, ...(false) && {b: "bye"},}
2 - Using Object.assign
Object.assign(a, conditionB ? { b: 1 } : null, conditionC ? { c: 2 } : null, conditionD ? { d: 3 } : null);
Object.assign modifies the first argument in-place while returning the updated object: so you can use it in a bigger formula to further manipulate the object.
You can pass undefined or {} instead of null, with the same result.
Number has no own enumerable properties, so you could even provide 0 instead since primitive values are wrapped.
For jQuery Developers
var a = $.extend({}, { b: conditionB ? 5 : undefined, c: conditionC ? 5 : undefined, // and so on...});
3 - To remove Undefined Values form Object not remove other falsely values like , 0 or null
const me = { name: prem, age: undefined , height: null}const cleanup = JSON.parse(JSON.stringify(me)); // { name: prem, height: null }
Shot Tip:-
Use !!value to get result in Boolean values if its truthy value the will return true otherwise False.
Eg:-
let isTruthy = hello console.log(!!isTruthy) // trueisTruthy = ; //can be 0 or undefined or nullConsole.log(!!isTruthy) // false
Original Link: https://dev.to/premjethwa/3-ways-to-add-conditional-properties-to-an-object--91n
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To