Search code examples
javascriptecmascript-6expressiondestructuring

Destructuring object based on expression


I want to know if you can use a dynamic expression when destructing an object:

Assume:

//basic de-structure example
var a = {b: 1};
var {b: c} = a; // stores 1 in c
//what I want to do
var { (b > 0): isItHigher = false} = a; // want isItHigher to be true

It might be a syntax I am not aware of, but, essentially, I want to evaluate an expression against the original object property and store it in a new variable. Is this possible?


Solution

  • You can do it by using destructuring defaults. The defaults can also include expressions based on values you've already extracted:

    var a = { b: 1 };
    var { b,  isItHigher = b > 0 } = a;
    
    console.log(isItHigher);

    @Anko notes a caveat: This method also creates a variable b, which may needlessly pollute the namespace depending on context.