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”})
}
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) // true
isTruthy = “”; //can be 0 or undefined or null
Console.log(!!isTruthy) // false
Top comments (0)