Enable an object literal to assign propertes directly from a variable's object

Say you want to construct a new object and use few fields from another object.

We do this:

const {sku, name, barcode, brand, unit} = item;
items[sku] = {name, barcode, brand, unit};

Why not allow this to extract the final variable name as a key and value:

items[item.sku] = {item.name, item.barcode, item.brand, item.unit};

The conventional first method leaves you with a duplicate and arguably unnecessary line of code. If I want to add or remove a field to extract into a new object, I require updating the other line.

I see this feature being cleaner with a negligible impact on readability and complexity. In fact it may reduce it by keeping variables effectively namespaced by the source object.

1 Like

Yes! There even is a proposal for this already, unfortunately it hasn't seen much advancement. I'd love to see this in the language!

Wasn't there already a way to do this that for various reasons, TC39 unwisely deprecated?

with(item) { items[sku] = {name, barcode, brand, unit}; }

Sadly, TC39 has gotten into the habit of trying to protect developers from their own ignorance lately and damaged useful features like this. If you're using ES modules or strict mode code, this won't work.

No, it was wisely deprecated. Your suggested solution breaks as soon as the item object contains an items property (e.g. when it's a tree representation), and that problem is very subtle.

1 Like

We can agree to disagree on that one. I've always been of the mindset that dangerous tools are useful when used carefully. Otherwise, imagine trying to get as far technologically as we have without mastering something as basic as fire.

Thank you for making an example of my point for me. Any developer trying to release code like what I wrote as part of a public library where the function might receive an object where items is a property of item needs to be careful to avoid that possibility, either by documenting that it's not allowed, and/or throwing if it happens.

[Rant On]
My point is that while it's nice to try and hand-hold developers through the development process, that's just not the job of the language. The job of the language is to provide functionality that is useful and makes a reasonable amount of sense. Lowering the floor of a house because a clumsy person keeps tripping at the threshold just makes it easier for the house to be flooded.

IMO, with is a useful feature. Sure it's easy to make mistakes with it, but it's always been up to the developer to be careful with whatever tools they choose to use. I'd dare say ASI is far more problematic than with, and the direction that class fields went is even more problematic. But like I said before, and TC39 basically relied on with their fields decisions, it's up to the developer to use the tools appropriately.
[Rant Off]

1 Like