DEV Community

Prem Jethwa
Prem Jethwa

Posted on • Edited on

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 Operator?
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”})
}
Enter fullscreen mode Exit fullscreen mode

Or

const greed = {
  ...(true) && {a: “hi”},
  ...(false) && {b: "bye"},
}
Enter fullscreen mode Exit fullscreen mode

2 - Using Object.assign


Object.assign(a, conditionB ? { b: 1 } : null,
                 conditionC ? { c: 2 } : null,
                 conditionD ? { d: 3 } : null);
Enter fullscreen mode Exit fullscreen mode

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...
});
Enter fullscreen mode Exit fullscreen mode

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 }

Enter fullscreen mode Exit fullscreen mode

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) // true

isTruthy = “”; //can be 0 or undefined or null

Console.log(!!isTruthy) // false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)