Destructuring - Assign selected props to a new variable

I often run into this scenario where in need of a portion of an object. destructuring surely helps in grabbing what is needed. the annoyance occur when the portion is used as a new object - forcing the code to like this:

const  {b, d} = {a: 10, b: 20, c: 30, d: 40}
someFunction({b,d});

this is a duplication of the properties and is a pitfall in some cases where you might leave out few properties unwillingly (when it comes to large portions from large objects).

a syntax such as the following might achieve better stability, assurance and nonrepetitive code.

const  {b, d} as newObj = {a: 10, b: 20, c: 30, d: 40}

it's currently possible to gather the rest of unmentioned properties with {...rest} but I think in most cases it is way more essential to select and group the destructured properties.

5 Likes

Are you familiar with the "as patterns" proposal?

IIRC, that's part of zkat's larger pattern matching proposal.

2 Likes

Seems just right. but this proposal is 2 years old and there's no evidence of progress :confused:
it is also really similiar and covers more patterns.

I'd vote for it!

1 Like

Unfortunately, zkat is not able to help with TC39 anymore through no fault of her own.

If someone did want to pick that up though, they could build on her work.

1 Like

zkat's current employer is an ecma member, so there's no barrier to their participation.

2 Likes

Hi, I've came across this issue and I'm also interested in it. Is there any way I can start help contribute to this proposal? Maybe I can help draft the stage-0 version of the as-proposal which is based on zkat's version.

Thanks!

1 Like

I think the property shorthand improvements proposal would have a much better chance at adoption, and is much more useful.

The syntax to achieve the goal from the OP's example:

const obj = {a: 10, b: 20, c: 30, d: 40}
someFunction({obj.b, obj.d});

wanna collaborate on this?

1 Like

|FRIEND I love your proposal is exactly what I have always needed.

const {b=1, d, e = 50} as newObj = {a: 10, b: 20, c: 30, d: 40}

i like this

console.log(newObject) // { b:20, d:40, e:50 }

I like this. Wish there was an easier way to do that.