Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
Conqueror Avatar asked Nov 29 '25 20:11

Conqueror


1 Answers

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.

like image 162
Ori Drori Avatar answered Dec 01 '25 11:12

Ori Drori