Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 13, 2022 08:21 am GMT

3 ways to add conditional properties to an object [...]

3 ways to add conditional properties to an object
1 - Using Spread Operator

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To